Internal
_destroyedHas this object been deliberately destroyed as part of the deletion workflow?
Internal
_objectThe source data object for this DataModel instance. Once constructed, the source object is sealed such that no keys may be added nor removed.
An immutable reverse-reference to a parent DataModel to which this model belongs.
Static
Internal
_schemaThe defined and cached Data Schema for all instances of this DataModel.
Static
LOCALIZATION_Static
metadataDefault metadata which applies to each instance of this Document type.
Static
nameReturn a reference to the parent Collection instance that contains this Document.
Test whether this Document is owned by any non-Gamemaster User.
The canonical identifier for this Document.
Is this document in a compendium? A stricter check than Document#inCompendium.
Is the current state of this DataModel invalid? The model is invalid if there is any unresolved failure.
Is this document embedded within a parent document?
A boolean indicator for whether the current game User has ownership rights for this Document. Different Document types may have more specialized rules for what constitutes ownership.
A reference to the CanvasLayer which contains Document objects of this type.
A boolean indicator for whether the current game User has exactly LIMITED visibility (and no greater).
Return a string which creates a dynamic link to this Document instance.
A lazily constructed PlaceableObject instance which can represent this Document on the game canvas.
Return the permission level that the current game User has over this Document. See the CONST.DOCUMENT_OWNERSHIP_LEVELS object for an enumeration of these levels.
An indicator for whether this document is currently rendered on the game canvas.
Define the data schema for this document instance.
Lazily obtain a Application instance used to configure this Document, or null if no sheet is available.
A Universally Unique Identifier (uuid) for this Document instance.
An array of validation failure instances which may have occurred when this instance was last validated.
A boolean indicator for whether the current game User has at least limited visibility for this Document. Different Document types may have more specialized rules for what determines visibility.
Static
baseThe base document definition that this document class extends from.
Static
collectionThe named collection to which this Document belongs.
Static
databaseThe database backend used to execute operations and handle results.
Static
documentThe canonical name of this Document type, for example "Actor".
Static
hasDoes this Document support additional subtypes?
Static
hierarchyThe Embedded Document hierarchy for this Document.
Static
implementationReturn a reference to the configured subclass of this base Document type.
Static
schemaEnsure that all Document classes share the same schema of their base declaration.
Static
TYPESThe allowed types which may exist for this Document class.
Internal
Create a content link for this document.
The parsed object of data provided by the drop transfer event.
Optional
options: { label?: string; relativeTo?: ClientDocument } = {}Additional options to configure link generation.
Optional
label?: stringA custom label to use instead of the document's name.
Optional
relativeTo?: ClientDocumentA document to generate a link relative to.
Internal
Orchestrate dispatching descendant document events to parent documents when embedded children are modified.
The event name, preCreate, onCreate, etc...
The collection name being modified within this parent document
Arguments passed to each dispatched function
Optional
_parent: ClientDocumentThe document with directly modified embedded documents. Either this document or a descendant of this one.
Internal
Identify the collection in a parent Document that this Document belongs to, if any.
Optional
parentCollection: null | stringAn explicitly provided parent collection name.
Internal
Obtain the Application class constructor which should be used to configure this Document.
Internal
Whenever the Document's sheet changes, close any existing applications for this Document, and re-render the new sheet if one was already open.
Optional
options: { sheetOpen?: boolean } = {}Optional
sheetOpen?: booleanWhether the sheet was originally open and needs to be re-opened.
Internal
Safely prepare data for a Document, catching any errors.
Test whether a given User has permission to perform some action on this Document
The User attempting modification
The attempted action
Optional
data: object = {}Data involved in the attempted action
Does the User have permission?
Clone a document, creating a new document by combining current data with provided overrides. The cloned document is ephemeral and not yet saved to the database.
Optional
data: object = {}Additional data which overrides current document data at the time of creation
Optional
context: DataModelConstructionOptions & Pick<Additional context options passed to the create method
The cloned Document instance
Create multiple embedded Document instances within this parent Document using provided input data.
The name of the embedded Document type
An array of data objects used to create multiple documents
Optional
operation: DatabaseCreateOperation = {}Parameters of the database creation workflow
An array of created Document instances
Delete this Document, removing it from the database.
Optional
operation: Partial<Omit<DatabaseDeleteOperation, "ids">> = {}Parameters of the deletion operation
The deleted Document instance, or undefined if not deleted
Present a Dialog form to confirm deletion of this Document.
Optional
options: object = {}Additional options passed to DialogV2.confirm
Optional
operation: DatabaseDeleteOperation = {}Document deletion options.
A Promise that resolves to the deleted Document
Delete multiple embedded Document instances within a parent Document using provided string ids.
The name of the embedded Document type
An array of string ids for each Document to be deleted
Optional
operation: DatabaseDeleteOperation = {}Parameters of the database deletion workflow
An array of deleted Document instances
Export document data to a JSON file which can be saved by the client and later imported into a different session. Only world Documents may be exported.
Optional
options: objectAdditional options passed to the ClientDocument#toCompendium method
Obtain a reference to the Array of source data within the data object for a certain embedded Document name
The name of the embedded Document type
The Collection instance of embedded Documents of the requested type
Get an embedded document by its id from a named collection in the parent document.
The name of the embedded Document type
The id of the child document to retrieve
Optional
options: { invalid?: boolean; strict?: boolean } = {}Additional options which modify how embedded documents are retrieved
Optional
invalid?: booleanAllow retrieving an invalid Embedded Document.
Optional
strict?: booleanThrow an Error if the requested id does not exist. See Collection#get
The retrieved embedded Document instance, or undefined
Get the value of a "flag" for this document See the setFlag method for more details on flags
The flag scope which namespaces the key
The flag key
The flag value
Construct a UUID relative to another document.
The document to compare against.
Get the explicit permission level that a User has over this Document, a value in CONST.DOCUMENT_OWNERSHIP_LEVELS. Compendium content ignores the ownership field in favor of User role-based ownership. Otherwise, Documents use granular per-User ownership definitions and Embedded Documents defer to their parent ownership.
This method returns the value recorded in Document ownership, regardless of the User's role, for example a GAMEMASTER user might still return a result of NONE if they are not explicitly denoted as having a level.
To test whether a user has a certain capability over the document, testUserPermission should be used.
Optional
user: BaseUserThe User being tested
A numeric permission level from CONST.DOCUMENT_OWNERSHIP_LEVELS
Update this Document using a provided JSON string. Only world Documents may be imported.
Raw JSON data to import
The updated Document instance
Render an import dialog for updating the data related to this Document through an exported JSON file
For Documents which include game system data, migrate the system data object to conform to its latest data model. The data model is defined by the template.json specification included by the game system.
The migrated system data object
Specific callback actions to take when the embedded HTML for this Document has been added to the DOM.
The embedded document HTML
Prepare data related to this Document itself, before any embedded Documents or derived data is computed.
If possible when modifying the system
object you should use
TypeDataModel#prepareBaseData on your data models
instead of this method directly on the document.
Prepare data for the Document. This method provides an opportunity for Document classes to define special data preparation logic to compute values that don't need to be stored in the database, such as a "bloodied" hp value or the total carrying weight of items. The work done by this method should be idempotent per initialization. There are situations in which prepareData may be called more than once.
By default, foundry calls the following methods in order whenever the document is created or updated.
Do NOT invoke database operations like update or setFlag within data prep, as that can cause an infinite loop by re-triggering the data initialization process.
If possible you should extend prepareBaseData and prepareDerivedData instead of this function directly, but some systems with more complicated calculations may want to override this function to add extra steps, such as to calculate certain item values after actor data prep.
Apply transformations or derivations to the values of the source data object. Compute data fields whose values are not stored to the database.
If possible when modifying the system
object you should use
TypeDataModel#prepareDerivedData on your data models
instead of this method directly on the document.
Prepare all embedded Document instances which exist within this primary Document.
Render all Application instances which are connected to this document by calling their respective
Optional
force: boolean = falseForce rendering
Optional
context: object = {}Optional context
Reset the state of this data instance back to mirror the contained source data, erasing any changes.
Assign a "flag" to this document. Flags represent key-value type data which can be used to store flexible or arbitrary data required by either the core software, game systems, or user-created modules.
Each flag should be set using a scope which provides a namespace for the flag to help prevent collisions.
Flags set by the core software use the "core" scope. Flags set by game systems or modules should use the canonical name attribute for the module Flags set by an individual world should "world" as the scope.
Flag values can assume almost any data type. Setting a flag value to null will delete that flag.
The flag scope which namespaces the key
The flag key
The flag value
A Promise resolving to the updated document
Determine the sort order for this Document by positioning it relative a target sibling. See SortingHelper.performIntegerSort for more details
Optional
options: { sortOptions?: object; updateData?: object } = {}Sorting options provided to SortingHelper.performIntegerSort
Optional
sortOptions?: objectOptions passed to the foundry.utils.performIntegerSort method
Optional
updateData?: objectAdditional data changes applied to each sorted document
The Document after it has been re-sorted
Test whether a certain User has a requested permission level (or greater) over the Document
The User being tested
The permission level from DOCUMENT_OWNERSHIP_LEVELS to test
Additional options involved in the permission test
Optional
exact?: booleanRequire the exact permission level requested?
Does the user have this permission level over the Document?
Create a content link for this Document.
Optional
options: any = {}Additional options to configure how the link is constructed.
Transform the Document data to be stored in a Compendium pack. Remove any features of the data which are world-specific.
Optional
pack: CompendiumCollection<any>A specific pack being exported to
Optional
options: {Additional options which modify how the document is converted
Optional
clearFlags?: booleanClear the flags object
Optional
clearFolder?: booleanClear the currently assigned folder
Optional
clearOwnership?: booleanClear document ownership (recursive)
Optional
clearSort?: booleanClear the currently assigned sort order
Optional
clearSource?: booleanClear any prior source information
Optional
clearState?: booleanClear fields which store document state (recursive)
Optional
keepId?: booleanRetain the current Document id
A data object of cleaned data suitable for compendium import
Serialize salient information about this Document when dragging it.
An object of drag data.
Convert a Document to some HTML display for embedding purposes.
Configuration for embedding behavior.
Optional
options: any = {}The original enrichment options for cases where the Document embed content also contains text that must be enriched.
A representation of the Document as HTML content, or null if such a representation could not be generated.
Extract the source data for the DataModel into a simple object format that can be serialized.
The document source data expressed as a plain object
Remove a flag assigned to the document
The flag scope which namespaces the key
The flag key
The updated document instance
Update this Document using incremental data, saving it to the database.
Optional
data: object = {}Differential update data which modifies the existing values of this document
Optional
operation: Partial<Omit<DatabaseUpdateOperation, "updates">> = {}Parameters of the update operation
The updated Document instance, or undefined not updated
Update multiple embedded Document instances within a parent Document using provided differential data.
The name of the embedded Document type
An array of differential data objects, each used to update a single Document
Optional
operation: DatabaseUpdateOperation = {}Parameters of the database update workflow
An array of updated Document instances
Update the DataModel locally by applying an object of changes to its source data. The provided changes are expanded, cleaned, validated, and stored to the source data object for this model. The provided changes argument is mutated in this process. The source data is then re-initialized to apply those changes to the prepared data. The method returns an object of differential changes which modified the original data.
New values which should be applied to the data model
Options which determine how the new data is merged
An object containing differential keys and values that were changed
Validate the data contained in the document to check for type and content. If changes are provided, missing types are added to it before cleaning and validation. This mutates the provided changes. This function throws an error if data within the document is not valid.
Options which modify how the model is validated
Whether the data source or proposed change is reported as valid. A boolean is always returned if validation is non-strict.
Protected
_buildProtected
A method that can be overridden by subclasses to customize embedded HTML generation.
Configuration for embedding behavior.
Optional
options: any = {}The original enrichment options for cases where the Document embed content also contains text that must be enriched.
Either a single root element to append, or a collection of elements that comprise the embedded content.
Protected
_createProtected
A method that can be overridden by subclasses to customize the generation of the embed figure.
The embedded content.
Configuration for embedding behavior.
Optional
options: anyThe original enrichment options for cases where the Document embed content also contains text that must be enriched.
Protected
_createProtected
A method that can be overridden by subclasses to customize inline embedded HTML generation.
The embedded content.
Optional
config: anyConfiguration for embedding behavior.
Optional
options: anyThe original enrichment options for cases where the Document embed content also contains text that must be enriched.
Protected
_initializeProtected
Initialize the source data for a new DataModel instance. One-time migrations and initial cleaning operations are applied to the source data.
The candidate source data from which the model will be constructed
Optional
options: object = {}Options provided to the model constructor
Migrated and cleaned source data which will be stored to the model instance,
which is the same object as the data
argument
Protected
_onProtected
Handle clicking on a content link for this document.
The triggering click event.
Protected
_onProtected
Actions taken after descendant documents have been created and changes have been applied to client data.
The direct parent of the created Documents, may be this Document or a child
The collection within which documents were created
The array of created Documents
The source data for new documents that were created
Options which modified the creation operation
The ID of the User who triggered the operation
Protected
_onProtected
Actions taken after descendant documents have been deleted and those deletions have been applied to client data.
The direct parent of the deleted Documents, may be this Document or a child
The collection within which documents were deleted
The array of Documents which were deleted
The array of document IDs which were deleted
Options which modified the deletion operation
The ID of the User who triggered the operation
Protected
_onProtected
Actions taken after descendant documents have been updated and changes have been applied to client data.
The direct parent of the updated Documents, may be this Document or a child
The collection within which documents were updated
The array of updated Documents
The array of differential Document updates which were applied
Options which modified the update operation
The ID of the User who triggered the operation
Protected
_preProtected
Actions taken after descendant documents have been created, but before changes are applied to the client data.
The direct parent of the created Documents, may be this Document or a child
The collection within which documents are being created
The source data for new documents that are being created
Options which modified the creation operation
The ID of the User who triggered the operation
Protected
_preProtected
Actions taken after descendant documents have been deleted, but before deletions are applied to the client data.
The direct parent of the deleted Documents, may be this Document or a child
The collection within which documents were deleted
The array of document IDs which were deleted
Options which modified the deletion operation
The ID of the User who triggered the operation
Protected
_preProtected
Actions taken after descendant documents have been updated, but before changes are applied to the client data.
The direct parent of the updated Documents, may be this Document or a child
The collection within which documents are being updated
The array of differential Document updates to be applied
Options which modified the update operation
The ID of the User who triggered the operation
Static
_addInternal
Define a simple migration from one field name to another. The value of the data can be transformed during the migration by an optional application function.
The data object being migrated
The old field name
The new field name
Optional
apply: (data: object) => anyAn application function, otherwise the old value is applied
Whether a migration was applied.
Static
_addInternal
A reusable helper for adding a migration shim The value of the data can be transformed during the migration by an optional application function.
The data object being shimmed
The old field name
The new field name
Optional
options: { value?: any; warning?: string } = {}Options passed to foundry.utils.logCompatibilityWarning
Optional
value?: anyThe value of the shim
Optional
warning?: stringThe deprecation message
Static
_addInternal
A reusable helper for adding migration shims.
The data object being shimmed
The mapping of old keys to new keys
Optional
options: { value?: any; warning?: string }Options passed to foundry.utils.logCompatibilityWarning
Optional
value?: anyThe value of the shim
Optional
warning?: stringThe deprecation message
Static
_clearInternal
Clear the fields from the given Document data recursively.
The (partial) Document data
The fields that are cleared
Static
_initializationStatic
_logInternal
Log a compatbility warning for the data field migration.
The old field name
The new field name
Optional
options: object = {}Options passed to foundry.utils.logCompatibilityWarning
Static
canTest whether a given User has sufficient permissions to create Documents of this type in general. This does not guarantee that the User is able to create all Documents of this type, as certain document-specific requirements may also be present.
Generally speaking, this method is used to verify whether a User should be presented with the option to create Documents of this type in the UI.
The User being tested
Does the User have a sufficient role to create?
Static
cleanClean a data source object to conform to a specific provided schema.
Optional
source: object = {}The source data object
Optional
options: object = {}Additional options which are passed to field cleaning methods
The cleaned source data, which is the same object as the source
argument
Static
createCreate a new Document using provided input data, saving it to the database.
Optional
data: Initial data used to create this Document, or a Document instance to persist.
Optional
operation: Partial<Omit<DatabaseCreateOperation, "data">> = {}Parameters of the creation operation
The created Document instance(s)
const data = [{name: "Special Sword", type: "weapon"}];
const created = await Item.implementation.create(data);
Static
createPresent a Dialog form to create a new Document of this type. Choose a name and a type from a select menu of types.
Document creation data
Optional
createOptions: DatabaseCreateOperation = {}Document creation options.
Optional
options: {Options forwarded to DialogV2.prompt
Optional
context?: objectAdditional render context to provide to the template.
Optional
folders?: { id: string; name: string }[]Available folders in which the new Document can be place
Optional
template?: stringA template to use for the dialog contents instead of the default.
Optional
types?: string[]A restriction of the selectable sub-types of the Dialog.
A Promise which resolves to the created Document, or null if the dialog was closed.
Static
createCreate multiple Documents using provided input data. Data is provided as an array of objects where each individual object becomes one new Document.
An array of data objects or existing Documents to persist.
Optional
operation: Partial<Omit<DatabaseCreateOperation, "data">> = {}Parameters of the requested creation operation
An array of created Document instances
const data = [{name: "New Actor", type: "character", img: "path/to/profile.jpg"}];
const created = await Actor.implementation.createDocuments(data);
const data = [{name: "Tim", type: "npc"], [{name: "Tom", type: "npc"}];
const created = await Actor.implementation.createDocuments(data);
Static
defaultGets the default new name for a Document
The context for which to create the Document name.
Optional
pack?: null | stringA compendium pack within which the Document should be created
Optional
parent?: null | Document<object, DocumentConstructionContext>A parent document within which the created Document should belong
Optional
type?: stringThe sub-type of the document
Static
Abstract
defineDefine the data schema for models of this type. The schema is populated the first time it is accessed and cached for future reuse.
The schema, through its fields, provide the essential cleaning, validation, and initialization methods to turn the _source values into direct properties of the data model. The schema is a static property of the model and is reused by all instances to perform validation.
The schemas defined by the core software in classes like foundry.documents.BaseActor are validated by the
server, where user code does not run. However, almost all documents have a flags
field to store data, and many
have a system
field that can be configured to be a foundry.abstract.TypeDataModel instance. Those models
are not constructed on the server and rely purely on client-side code, which means certain extra-sensitive fields
must be also be registered through your package manifest. foundry.packages.types.ServerSanitizationFields
class SomeModel extends foundry.abstract.DataModel {
static defineSchema() {
return {
foo: new foundry.data.fields.StringField()
}
}
}
class AnotherModel extends SomeModel {
static defineSchema() {
// Inheritance and object oriented principles apply to schema definition
const schema = super.defineSchema()
schema.bar = new foundry.data.fields.NumberField()
return schema;
}
}
Static
deleteDelete one or multiple existing Documents using an array of provided ids. Data is provided as an array of string ids for the documents to delete.
An array of string ids for the documents to be deleted
Optional
operation: Partial<Omit<DatabaseDeleteOperation, "ids">> = {}Parameters of the database deletion operation
An array of deleted Document instances
const tim = game.actors.getName("Tim");
const deleted = await Actor.implementation.deleteDocuments([tim.id]);
const tim = game.actors.getName("Tim");
const tom = game.actors.getName("Tom");
const deleted = await Actor.implementation.deleteDocuments([tim.id, tom.id]);
Static
fromA helper function to handle obtaining the relevant Document from dropped data provided via a DataTransfer event. The dropped data could have:
The data object extracted from a DataTransfer event
The resolved Document
Static
fromCreate the Document from the given source with migration applied to it. Only primary Documents may be imported.
This function must be used to create a document from data that predates the current core version. It must be given nonpartial data matching the schema it had in the core version it is coming from. It applies legacy migrations to the source data before calling foundry.abstract.Document.fromSource. If this function is not used to import old data, necessary migrations may not applied to the data resulting in an incorrectly imported document.
The core version is recorded in the _stats
field, which all primary documents have. If the given source data
doesn't contain a _stats
field, the data is assumed to be pre-V10, when the _stats
field didn't exist yet.
The _stats
field must not be stripped from the data before it is exported!
The document data that is imported.
Optional
context: DocumentConstructionContextThe model construction context passed to foundry.abstract.Document.fromSource. Strict validation is enabled by default.
Static
fromJSONCreate a DataModel instance using a provided serialized JSON string.
Serialized document data in string format
A constructed data model instance
Static
fromCreate a new instance of this DataModel from a source record. The source is presumed to be trustworthy and is not strictly validated.
Initial document data which comes from a trusted source.
Optional
context: Omit<DataModelConstructionContext, "strict"> & DataModelFromSourceOptions = {}Model construction context
Static
getGet a World-level Document of this type by its id.
The Document ID
Optional
operation: DatabaseGetOperation = {}Parameters of the get operation
The retrieved Document, or null
Static
getA compatibility method that returns the appropriate name of an embedded collection within this Document.
An existing collection name or a document name.
The provided collection name if it exists, the first available collection for the document name provided, or null if no appropriate embedded collection could be found.
Static
migrateMigrate candidate source data for this DataModel which may require initial cleaning or transformations.
The candidate source data from which the model will be constructed
Migrated source data, which is the same object as the source
argument
Static
migrateWrap data migration in a try/catch which attempts it safely
The candidate source data from which the model will be constructed
Migrated source data, which is the same object as the source
argument
Static
shimTake data which conforms to the current data schema and add backwards-compatible accessors to it in order to support older code which uses this data.
Data which matches the current schema
Optional
options: { embedded?: boolean } = {}Additional shimming options
Optional
embedded?: booleanApply shims to embedded models?
Data with added backwards-compatible properties, which is the same object as
the data
argument
Static
updateUpdate multiple Document instances using provided differential data. Data is provided as an array of objects where each individual object updates one existing Document.
An array of differential data objects, each used to update a single Document
Optional
operation: Partial<Omit<DatabaseUpdateOperation, "updates">> = {}Parameters of the database update operation
An array of updated Document instances
const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}];
const updated = await Actor.implementation.updateDocuments(updates);
const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}, {_id: "kj549dk48k34jk34", name: "Thomas"}]};
const updated = await Actor.implementation.updateDocuments(updates);
Static
validateEvaluate joint validation rules which apply validation conditions across multiple fields of the model. Field-specific validation rules should be defined as part of the DataSchema for the model. This method allows for testing aggregate rules which impose requirements on the overall model.
Candidate data for the model
Protected
Static
_onProtected
Post-process a creation operation, reacting to database changes which have occurred. Post-operation events occur for all connected clients.
This batch-wise workflow occurs after individual _onCreate workflows.
The Document instances which were created
Parameters of the database creation operation
The User who performed the creation operation
Protected
Static
_onProtected
Post-process a deletion operation, reacting to database changes which have occurred. Post-operation events occur for all connected clients.
This batch-wise workflow occurs after individual _onDelete workflows.
The Document instances which were deleted
Parameters of the database deletion operation
The User who performed the deletion operation
Protected
Static
_onProtected
Post-process an update operation, reacting to database changes which have occurred. Post-operation events occur for all connected clients.
This batch-wise workflow occurs after individual _onUpdate workflows.
The Document instances which were updated
Parameters of the database update operation
The User who performed the update operation
Protected
Static
_preProtected
Pre-process a creation operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.
This batch-wise workflow occurs after individual _preCreate workflows and provides a final pre-flight check before a database operation occurs.
Modifications to pending documents must mutate the documents array or alter individual document instances using updateSource.
Pending document instances to be created
Parameters of the database creation operation
The User requesting the creation operation
Return false to cancel the creation operation entirely
Protected
Static
_preProtected
Pre-process a deletion operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.
This batch-wise workflow occurs after individual _preDelete workflows and provides a final pre-flight check before a database operation occurs.
Modifications to the requested deletions are performed by mutating the operation object. updateSource.
Document instances to be deleted
Parameters of the database update operation
The User requesting the deletion operation
Return false to cancel the deletion operation entirely
Protected
Static
_preProtected
Pre-process an update operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.
This batch-wise workflow occurs after individual _preUpdate workflows and provides a final pre-flight check before a database operation occurs.
Modifications to the requested updates are performed by mutating the data array of the operation.
Document instances to be updated
Parameters of the database update operation
The User requesting the update operation
Return false to cancel the update operation entirely
A ClientDocument class with additional facilities for utilizing the foundry.canvas.Canvas API