The 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.
StaticLOCALIZATION_StaticmetadataDefault metadata which applies to each instance of this Document type.
StaticnameReturn 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 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.
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.
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.
StaticbaseThe base document definition that this document class extends from.
StaticcollectionThe named collection to which this Document belongs.
StaticdatabaseThe database backend used to execute operations and handle results.
StaticdocumentThe canonical name of this Document type, for example "Actor".
StatichasDoes this Document support additional subtypes?
StatichierarchyThe Embedded Document hierarchy for this Document.
StaticimplementationReturn a reference to the configured subclass of this base Document type.
StaticschemaEnsure that all Document classes share the same schema of their base declaration.
StaticTYPESThe allowed types which may exist for this Document class.
InternalCreate a content link for this document.
The parsed object of data provided by the drop transfer event.
Optionaloptions: { label?: string; relativeTo?: ClientDocument } = {}Additional options to configure link generation.
Optionallabel?: stringA custom label to use instead of the document's name.
OptionalrelativeTo?: ClientDocumentA document to generate a link relative to.
InternalOrchestrate 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.
InternalIdentify the collection in a parent Document that this Document belongs to, if any.
OptionalparentCollection: null | stringAn explicitly provided parent collection name.
InternalObtain the Application class constructor which should be used to configure this Document.
InternalWhenever the Document's sheet changes, close any existing applications for this Document, and re-render the new sheet if one was already open.
Optionaloptions: { sheetOpen?: boolean } = {}OptionalsheetOpen?: booleanWhether the sheet was originally open and needs to be re-opened.
InternalSafely 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
Optionaldata: 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.
Optionaldata: object = {}Additional data which overrides current document data at the time of creation
Optionalcontext: 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
Optionaloperation: DatabaseCreateOperation = {}Parameters of the database creation workflow
An array of created Document instances
Delete this Document, removing it from the database.
Optionaloperation: 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.
Optionaloptions: object = {}Additional options passed to DialogV2.confirm
Optionaloperation: 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
Optionaloperation: 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.
Optionaloptions: object = {}Additional 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
Optionaloptions: { invalid?: boolean; strict?: boolean } = {}Additional options which modify how embedded documents are retrieved
Optionalinvalid?: booleanAllow retrieving an invalid Embedded Document.
Optionalstrict?: 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.
Optionaluser: 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
Optionalforce: boolean = falseForce rendering
Optionalcontext: 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
Optionaloptions: { sortOptions?: object; updateData?: object } = {}Sorting options provided to SortingHelper.performIntegerSort
OptionalsortOptions?: objectOptions passed to the foundry.utils.performIntegerSort method
OptionalupdateData?: 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
Optionalexact?: booleanRequire the exact permission level requested?
Does the user have this permission level over the Document?
Create a content link for this Document.
Optionaloptions: 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.
Optionalpack: CompendiumCollection<any>A specific pack being exported to
Optionaloptions: {Additional options which modify how the document is converted
OptionalclearFlags?: booleanClear the flags object
OptionalclearFolder?: booleanClear the currently assigned folder
OptionalclearOwnership?: booleanClear document ownership (recursive). Default ownership is preserved.
OptionalclearSort?: booleanClear the currently assigned sort order
OptionalclearSource?: booleanClear any prior source information
OptionalclearState?: booleanClear fields which store document state (recursive)
OptionalkeepId?: 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.
Optionaloptions: 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.
Optionaldata: object = {}Differential update data which modifies the existing values of this document
Optionaloperation: 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
Optionaloperation: 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_buildProtectedA method that can be overridden by subclasses to customize embedded HTML generation.
Configuration for embedding behavior.
Optionaloptions: 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_createProtectedA method that can be overridden by subclasses to customize the generation of the embed figure.
The embedded content.
Configuration for embedding behavior.
Optionaloptions: anyThe original enrichment options for cases where the Document embed content also contains text that must be enriched.
Protected_createProtectedA method that can be overridden by subclasses to customize inline embedded HTML generation.
The embedded content.
Optionalconfig: anyConfiguration for embedding behavior.
Optionaloptions: anyThe original enrichment options for cases where the Document embed content also contains text that must be enriched.
Protected_initializeProtectedInitialize 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
Optionaloptions: 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_onProtectedHandle clicking on a content link for this document.
The triggering click event.
Protected_onProtectedActions 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_onProtectedActions 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_onProtectedActions 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_preProtectedActions 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_preProtectedActions 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_preProtectedActions 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_addInternalDefine 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
Optionalapply: (data: object) => anyAn application function, otherwise the old value is applied
Whether a migration was applied.
Static_addInternalA 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
Optionaloptions: { value?: any; warning?: string } = {}Options passed to foundry.utils.logCompatibilityWarning
Optionalvalue?: anyThe value of the shim
Optionalwarning?: stringThe deprecation message
Static_addInternalA reusable helper for adding migration shims.
The data object being shimmed
The mapping of old keys to new keys
Optionaloptions: { value?: any; warning?: string }Options passed to foundry.utils.logCompatibilityWarning
Optionalvalue?: anyThe value of the shim
Optionalwarning?: stringThe deprecation message
Static_clearInternalClear the fields from the given Document data recursively.
The (partial) Document data
The fields that are cleared
Optionaloptions: { callback?: RecursiveFieldClearCallback } = {}Optionalcallback?: RecursiveFieldClearCallbackA callback that is invoked on each field in order to clear it.
Static_initializationStatic_logInternalLog a compatbility warning for the data field migration.
The old field name
The new field name
Optionaloptions: object = {}Options passed to foundry.utils.logCompatibilityWarning
StaticcanTest 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?
StaticcleanClean a data source object to conform to a specific provided schema.
Optionalsource: object = {}The source data object
Optionaloptions: object = {}Additional options which are passed to field cleaning methods
The cleaned source data, which is the same object as the source argument
StaticcreateCreate a new Document using provided input data, saving it to the database.
Optionaldata: Initial data used to create this Document, or a Document instance to persist.
Optionaloperation: 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);
StaticcreatePresent 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
OptionalcreateOptions: DatabaseCreateOperation = {}Document creation options.
Optionaloptions: {Options forwarded to DialogV2.prompt
Optionalcontext?: objectAdditional render context to provide to the template.
Optionalfolders?: { id: string; name: string }[]Available folders in which the new Document can be place
Optionaltemplate?: stringA template to use for the dialog contents instead of the default.
Optionaltypes?: 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.
StaticcreateCreate 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.
Optionaloperation: 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);
StaticdefaultGets the default new name for a Document
The context for which to create the Document name.
Optionalpack?: null | stringA compendium pack within which the Document should be created
Optionalparent?: null | Document<object, DocumentConstructionContext>A parent document within which the created Document should belong
Optionaltype?: stringThe sub-type of the document
Static AbstractdefineDefine 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;
}
}
StaticdeleteDelete 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
Optionaloperation: 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]);
StaticfromA 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
StaticfromCreate 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.
Optionalcontext: DocumentConstructionContextThe model construction context passed to foundry.abstract.Document.fromSource. Strict validation is enabled by default.
StaticfromJSONCreate a DataModel instance using a provided serialized JSON string.
Serialized document data in string format
A constructed data model instance
StaticfromCreate 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.
Optionalcontext: Omit<DataModelConstructionContext, "strict"> & DataModelFromSourceOptions = {}Model construction context
StaticgetGet a World-level Document of this type by its id.
The Document ID
Optionaloperation: DatabaseGetOperation = {}Parameters of the get operation
The retrieved Document, or null
StaticgetA 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.
StaticmigrateMigrate 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
StaticmigrateWrap 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
StaticshimTake 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
Optionaloptions: { embedded?: boolean } = {}Additional shimming options
Optionalembedded?: booleanApply shims to embedded models?
Data with added backwards-compatible properties, which is the same object as
the data argument
StaticupdateUpdate 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
Optionaloperation: 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);
StaticvalidateEvaluate 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_onProtectedPost-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_onProtectedPost-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_onProtectedPost-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_preProtectedPre-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_preProtectedPre-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_preProtectedPre-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
The ClientDocument extends the base Document class by adding client-specific behaviors to all Document types.