Foundry Virtual Tabletop - API Documentation - Version 14
    Preparing search index...

    Class ClientDocument

    The ClientDocument extends the base Document class by adding client-specific behaviors to all Document types.

    Hierarchy (View Summary)

    Index

    Properties

    Accessors

    Methods

    _configure _createDocumentLink _dispatchDescendantDocumentEvents _getParentCollection _getSheetClass _initializationOrder _initialize _onCreate _onDelete _onSheetChange _onUpdate _preCreate _preDelete _preUpdate _safePrepareData _updateDiff canUserModify clone createEmbeddedDocuments delete deleteDialog deleteEmbeddedDocuments exportToJSON getEmbeddedCollection getEmbeddedDocument getFieldForProperty getFlag getUserLevel importFromJSON importFromJSONDialog migrateSystemData onEmbed prepareBaseData prepareData prepareDerivedData prepareEmbeddedDocuments render reset setFlag sortRelative testUserPermission toAnchor toCompendium toDragData toEmbed toJSON toObject traverseEmbeddedDocuments unsetFlag update updateEmbeddedDocuments updateSource validate _buildEmbedHTML _createFigureEmbed _createInlineEmbed _initializeSource _onClickDocumentLink _onCreateDescendantDocuments _onDeleteDescendantDocuments _onUpdateDescendantDocuments _preCreateDescendantDocuments _preDeleteDescendantDocuments _preUpdateDescendantDocuments _preUpdateSource _updateCommit _addDataFieldMigration _addDataFieldShim _addDataFieldShims _clearFieldsRecursively _logDataFieldMigration _onCreateOperation _preCleanData canUserCreate cleanData create createDialog createDocuments defaultName defineSchema deleteDocuments fromDropData fromImport fromJSON fromSource get getCollectionName migrateData migrateDataSafe shimData updateDocuments validateJoint _cleanData _onDeleteOperation _onUpdateOperation _preCreateOperation _preDeleteOperation _preUpdateOperation

    Properties

    _source: object

    The source data object for this DataModel instance. Once constructed, the source object is sealed such that no keys may be added nor removed.

    parent: DataModel<object, DataModelConstructionContext> | null

    An immutable reverse-reference to a parent DataModel to which this model belongs.

    The defined and cached Data Schema for all instances of this DataModel.

    LOCALIZATION_PREFIXES: string[] = ...
    metadata: Readonly<DocumentClassMetadata> = ...

    Default metadata which applies to each instance of this Document type.

    name: string = "ClientDocumentMixin"

    Accessors

    • get collection(this: ClientDocument): any

      Return a reference to the parent Collection/Document instance that contains/is this Document.

      Parameters

      Returns any

    • get hasPlayerOwner(): boolean

      Test whether this Document is owned by any non-Gamemaster User.

      Returns boolean

    • get id(): string | null

      The canonical identifier for this Document.

      Returns string | null

    • get inCompendium(): boolean

      Is this document in a compendium? A stricter check than Document#inCompendium.

      Returns boolean

    • get invalid(): boolean

      Is the current state of this DataModel invalid? The model is invalid if there is any unresolved failure.

      Returns boolean

    • get isEmbedded(): boolean

      Is this document embedded within a parent document?

      Returns boolean

    • get isOwner(): boolean

      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.

      Returns boolean

    • get limited(): boolean

      A boolean indicator for whether the current game User has exactly LIMITED visibility (and no greater).

      Returns boolean

    • Return a string which creates a dynamic link to this Document instance.

      Returns string

    • get permission(): number

      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.

      Returns number

      game.user.id; // "dkasjkkj23kjf"
      actor.data.permission; // {default: 1, "dkasjkkj23kjf": 2};
      actor.permission; // 2
    • get persisted(): boolean

      Is this Document persisted?

      A document is persisted if it has a nonnull UUID that resolves to a document with fromUuid. In particular, clones of persisted Documents are also persisted Documents if they have the same ID as the original.

      This property is false until this document and all its ancestors up to the root document have been initialized and added to their collections.

      Returns boolean

    • get uuid(): string

      A Universally Unique Identifier (uuid) for this Document instance.

      Returns string

    • get visible(): boolean

      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.

      Returns boolean

    • get baseDocument(): typeof Document

      The base document definition that this document class extends from.

      Returns typeof Document

    • get collectionName(): string

      The named collection to which this Document belongs.

      Returns string

    • get documentName(): string

      The canonical name of this Document type, for example "Actor".

      Returns string

    • get hasTypeData(): boolean

      Does this Document support additional subtypes?

      Returns boolean

    • get hierarchy(): Readonly<Record<string, any>>

      The Embedded Document hierarchy for this Document.

      Returns Readonly<Record<string, any>>

    • get implementation(): typeof Document

      Return a reference to the configured subclass of this base Document type.

      Returns typeof Document

    • get TYPES(): string[]

      The allowed types which may exist for this Document class.

      Returns string[]

    Methods

    • Parameters

      • __namedParameters: { pack?: null; parentCollection?: null } = {}

      Returns void

    • Internal

      Create a content link for this document.

      Parameters

      • eventData: object

        The parsed object of data provided by the drop transfer event.

      • Optionaloptions: { label?: string; relativeTo?: ClientDocument } = {}

        Additional options to configure link generation.

        • Optionallabel?: string

          A custom label to use instead of the document's name.

        • OptionalrelativeTo?: ClientDocument

          A document to generate a link relative to.

      Returns string

    • Internal

      Orchestrate dispatching descendant document events to parent documents when embedded children are modified.

      Parameters

      • event: string

        The event name, preCreate, onCreate, etc...

      • collection: string

        The collection name being modified within this parent document

      • args: any[]

        Arguments passed to each dispatched function

      • Optional_parent: ClientDocument

        The document with directly modified embedded documents. Either this document or a descendant of this one.

      Returns void

    • Internal

      Identify the collection in a parent Document that this Document belongs to, if any.

      Parameters

      • OptionalparentCollection: string | null

        An explicitly provided parent collection name.

      Returns string | null

    • Internal

      Obtain the Application class constructor which should be used to configure this Document.

      Returns Function | null

    • Returns Generator<(string | DataField | undefined)[], void, unknown>

    • Parameters

      Returns void

    • Parameters

      • data: any
      • options: any
      • userId: any

      Returns void

    • Parameters

      • options: any
      • userId: any

      Returns void

    • 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.

      Parameters

      • Optionaloptions: { sheetOpen?: boolean } = {}
        • OptionalsheetOpen?: boolean

          Whether the sheet was originally open and needs to be re-opened.

      Returns Promise<void>

    • Parameters

      • changed: any
      • options: any
      • userId: any

      Returns void

    • Parameters

      • data: any
      • options: any
      • user: any

      Returns Promise<any>

    • Parameters

      • options: any
      • user: any

      Returns Promise<any>

    • Parameters

      • changes: any
      • options: any
      • user: any

      Returns Promise<any>

    • Internal

      Safely prepare data for a Document, catching any errors.

      Returns void

    • Parameters

      • copy: any
      • changes: any
      • options: any
      • _state: any

      Returns object

    • Test whether a given User has permission to perform some action on this Document

      Parameters

      • user: BaseUser

        The User attempting modification

      • action: string

        The attempted action

      • Optionaldata: object = {}

        Data involved in the attempted action

      Returns boolean

      Does the User have permission?

    • 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.

      Parameters

      Returns void

    • Obtain a reference to the Array of source data within the data object for a certain embedded Document name

      Parameters

      • embeddedName: string

        The name of the embedded Document type

      Returns DocumentCollection

      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.

      Parameters

      • embeddedName: string

        The name of the embedded Document type

      • id: string

        The id of the child document to retrieve

      • Optionaloptions: { invalid?: boolean; strict?: boolean } = {}

        Additional options which modify how embedded documents are retrieved

        • Optionalinvalid?: boolean

          Allow retrieving an invalid Embedded Document.

        • Optionalstrict?: boolean

          Throw an Error if the requested id does not exist. See Collection#get

      Returns Document<object, DocumentConstructionContext>

      The retrieved embedded Document instance, or undefined

      If the embedded collection does not exist, or if strict is true and the Embedded Document could not be found.

    • Traverse the data model instance, obtaining the DataField definition for a field of a particular property.

      Parameters

      • key: string | string[]

        A property key like ["abilities", "strength"] or "abilities.strength"

      Returns DataField | undefined

      The corresponding DataField definition for that field, or undefined

    • Get the value of a "flag" for this document See the setFlag method for more details on flags

      Parameters

      • scope: string

        The flag scope which namespaces the key

      • key: string

        The flag key

      Returns any

      The flag value

    • 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.

      Parameters

      • Optionaluser: BaseUser

        The User being tested

      Returns DocumentOwnershipNumber

      A numeric permission level from CONST.DOCUMENT_OWNERSHIP_LEVELS

    • Update this Document using a provided JSON string. Only world Documents may be imported.

      Parameters

      Returns Promise<ClientDocument>

      The updated Document instance

    • Render an import dialog for updating the data related to this Document through an exported JSON file

      Returns Promise<void>

    • 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.

      Returns object

      The migrated system data object

    • Specific callback actions to take when the embedded HTML for this Document has been added to the DOM.

      Parameters

      • element: HTMLDocumentEmbedElement

        The embedded document HTML

      Returns void

    • 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.

      Returns void

    • 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.

      1. reset (Inherited from DataModel)
      2. _initialize (Inherited from DataModel)
      3. prepareData
      4. TypeDataModel#prepareBaseData
      5. prepareBaseData
      6. prepareEmbeddedDocuments
      7. TypeDataModel#prepareBaseData
      8. prepareDerivedData

      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.

      Returns void

    • 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.

      Returns void

    • Prepare all embedded Document instances which exist within this primary Document.

      Returns void

    • Render all Application instances which are connected to this document by calling their respective

      Parameters

      • Optionalforce: boolean = false

        Force rendering

      • Optionalcontext: object = {}

        Optional context

      Returns void

    • Reset the state of this data instance back to mirror the contained source data, erasing any changes.

      Returns void

    • 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.

      Parameters

      • scope: string

        The flag scope which namespaces the key

      • key: string

        The flag key

      • value: any

        The flag value

      Returns Promise<Document<object, DocumentConstructionContext>>

      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

      Parameters

      • Optionaloptions: { sortOptions?: object; updateData?: object } = {}

        Sorting options provided to SortingHelper.performIntegerSort

        • OptionalsortOptions?: object

          Options passed to the foundry.utils.performIntegerSort method

        • OptionalupdateData?: object

          Additional data changes applied to each sorted document

      Returns Promise<Document<object, DocumentConstructionContext>>

      The Document after it has been re-sorted

    • Test whether a certain User has a requested permission level (or greater) over the Document

      Parameters

      • user: BaseUser

        The User being tested

      • permission: DocumentOwnershipLevel

        The permission level from DOCUMENT_OWNERSHIP_LEVELS to test

      • options: { exact?: boolean } = {}

        Additional options involved in the permission test

        • Optionalexact?: boolean

          Require the exact permission level requested?

      Returns boolean

      Does the user have this permission level over the Document?

    • Create a content link for this Document.

      Parameters

      • Optionaloptions: any = {}

        Additional options to configure how the link is constructed.

      Returns HTMLAnchorElement

    • Transform the Document data to be stored in a Compendium pack. Remove any features of the data which are world-specific.

      Parameters

      Returns object

      A data object of cleaned data suitable for compendium import

    • Serialize salient information about this Document when dragging it.

      Returns object

      An object of drag data.

    • Convert a Document to some HTML display for embedding purposes.

      Parameters

      • config: DocumentHTMLEmbedConfig

        Configuration for embedding behavior.

      • Optionaloptions: any = {}

        The original enrichment options for cases where the Document embed content also contains text that must be enriched.

      Returns Promise<any>

      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.

      Returns object

      The document source data expressed as a plain object

    • Parameters

      • source: boolean = true

      Returns any

    • Iterate over all embedded Documents that are hierarchical children of this Document.

      Parameters

      • Optional_parentPath: string

        A parent field path already traversed

      Returns Generator<any, void, any>

    • Remove a flag assigned to the document.

      Parameters

      • scope: string

        The flag scope which namespaces the key

      • key: string

        The flag key

      Returns Promise<Document<object, DocumentConstructionContext>>

      The updated document instance

    • Update multiple embedded Document instances within a parent Document using provided differential data.

      Parameters

      • embeddedName: string

        The name of the embedded Document type

      • updates: object[] = []

        An array of differential data objects, each used to update a single Document

      • Optionaloperation: DatabaseUpdateOperation = {}

        Parameters of the database update workflow

      Returns Promise<Document<object, DocumentConstructionContext>[]>

      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.

      Parameters

      • changes: object = {}

        New values which should be applied to the data model

      • options: DataModelUpdateOptions = {}

        Options which determine how the new data is merged

      Returns object

      An object containing differential keys and values that were changed

      An error if the requested data model changes were invalid

    • Validate the data contained in the document to check for type and content. This method is intended to validate complete model records, verifying both individual field validation as well as joint model validity.

      For validating sets of partial model changes, it is preferred to call DataModel#updateSource as a dryRun. This method provides a convenience alias for such a workflow if changes are provided.

      Warning: if fallback handling is allowed, this process will mutate provided changes or model source data.

      Parameters

      Returns boolean

      Whether the data source or proposed change is reported as valid. A boolean is always returned if validation is non-strict.

      An error thrown if validation is strict and a failure occurs.

    • Protected

      A method that can be overridden by subclasses to customize embedded HTML generation.

      Parameters

      • config: DocumentHTMLEmbedConfig

        Configuration for embedding behavior.

      • Optionaloptions: any = {}

        The original enrichment options for cases where the Document embed content also contains text that must be enriched.

      Returns Promise<HTMLElement | HTMLCollection | null>

      Either a single root element to append, or a collection of elements that comprise the embedded content.

    • Protected

      A method that can be overridden by subclasses to customize the generation of the embed figure.

      Parameters

      • content: HTMLElement | HTMLCollection

        The embedded content.

      • config: DocumentHTMLEmbedConfig

        Configuration for embedding behavior.

      • Optionaloptions: any

        The original enrichment options for cases where the Document embed content also contains text that must be enriched.

      Returns Promise<HTMLElement | null>

    • Protected

      A method that can be overridden by subclasses to customize inline embedded HTML generation.

      Parameters

      • content: HTMLElement | HTMLCollection

        The embedded content.

      • Optionalconfig: any

        Configuration for embedding behavior.

      • Optionaloptions: any

        The original enrichment options for cases where the Document embed content also contains text that must be enriched.

      Returns Promise<HTMLElement | null>

    • Protected

      Initialize the source data for a new DataModel instance. One-time migrations and initial cleaning operations are applied to the source data.

      Parameters

      Returns object

      Migrated and cleaned source data which will be stored to the model instance, which is the same object as the data argument

    • Protected

      Actions taken after descendant documents have been created and changes have been applied to client data.

      Parameters

      • parent: Document<object, DocumentConstructionContext>

        The direct parent of the created Documents, may be this Document or a child

      • collection: string

        The collection within which documents were created

      • documents: Document<object, DocumentConstructionContext>[]

        The array of created Documents

      • data: object[]

        The source data for new documents that were created

      • options: object

        Options which modified the creation operation

      • userId: string

        The ID of the User who triggered the operation

      Returns void

    • Protected

      Actions taken after descendant documents have been deleted and those deletions have been applied to client data.

      Parameters

      • parent: Document<object, DocumentConstructionContext>

        The direct parent of the deleted Documents, may be this Document or a child

      • collection: string

        The collection within which documents were deleted

      • documents: Document<object, DocumentConstructionContext>[]

        The array of Documents which were deleted

      • ids: string[]

        The array of document IDs which were deleted

      • options: object

        Options which modified the deletion operation

      • userId: string

        The ID of the User who triggered the operation

      Returns void

    • Protected

      Actions taken after descendant documents have been updated and changes have been applied to client data.

      Parameters

      • parent: Document<object, DocumentConstructionContext>

        The direct parent of the updated Documents, may be this Document or a child

      • collection: string

        The collection within which documents were updated

      • documents: Document<object, DocumentConstructionContext>[]

        The array of updated Documents

      • changes: object[]

        The array of differential Document updates which were applied

      • options: object

        Options which modified the update operation

      • userId: string

        The ID of the User who triggered the operation

      Returns void

    • Protected

      Actions taken after descendant documents have been created, but before changes are applied to the client data.

      Parameters

      • parent: Document<object, DocumentConstructionContext>

        The direct parent of the created Documents, may be this Document or a child

      • collection: string

        The collection within which documents are being created

      • data: object[]

        The source data for new documents that are being created

      • options: object

        Options which modified the creation operation

      • userId: string

        The ID of the User who triggered the operation

      Returns void

    • Protected

      Actions taken after descendant documents have been deleted, but before deletions are applied to the client data.

      Parameters

      • parent: Document<object, DocumentConstructionContext>

        The direct parent of the deleted Documents, may be this Document or a child

      • collection: string

        The collection within which documents were deleted

      • ids: string[]

        The array of document IDs which were deleted

      • options: object

        Options which modified the deletion operation

      • userId: string

        The ID of the User who triggered the operation

      Returns void

    • Protected

      Actions taken after descendant documents have been updated, but before changes are applied to the client data.

      Parameters

      • parent: Document<object, DocumentConstructionContext>

        The direct parent of the updated Documents, may be this Document or a child

      • collection: string

        The collection within which documents are being updated

      • changes: object[]

        The array of differential Document updates to be applied

      • options: object

        Options which modified the update operation

      • userId: string

        The ID of the User who triggered the operation

      Returns void

    • Protected

      Perform the second step of the DataModel#_updateSource workflow which applies the prepared diff to the model.

      Parameters

      • copy: object

        The prepared copy of source data with changes applied

      • diff: object

        The differential changes that were applied to source

      • options: DataModelUpdateOptions

        Options which determine how the new data is merged

      • _state: data.types.DataModelUpdateState

        Data cleaning state which might include instructions for final commit

      Returns void

    • Internal

      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.

      Parameters

      • data: object

        The data object being migrated

      • oldKey: string

        The old field name

      • newKey: string

        The new field name

      • Optionalapply: (data: object) => any

        An application function, otherwise the old value is applied

      Returns boolean

      Whether a migration was applied.

    • Internal

      A reusable helper for adding a migration shim The value of the data can be transformed during the migration by an optional application function.

      Parameters

      • data: object

        The data object being shimmed

      • oldKey: string

        The old field name

      • newKey: string

        The new field name

      • Optionaloptions: { value?: any; warning?: string } = {}
        • Optionalvalue?: any

          The value of the shim

        • Optionalwarning?: string

          The deprecation message

      Returns void

    • Internal

      A reusable helper for adding migration shims.

      Parameters

      • data: object

        The data object being shimmed

      • shims: { [oldKey: string]: string }

        The mapping of old keys to new keys

      • Optionaloptions: { value?: any; warning?: string }
        • Optionalvalue?: any

          The value of the shim

        • Optionalwarning?: string

          The deprecation message

      Returns void

    • Internal

      Clear the fields from the given Document data recursively.

      Parameters

      Returns void

    • Internal

      Log a compatbility warning for the data field migration.

      Parameters

      Returns void

    • Parameters

      • documents: any
      • operation: any
      • user: any

      Returns Promise<void>

    • Parameters

      • data: any
      • options: any
      • _state: any

      Returns void

    • Test 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.

      Parameters

      Returns boolean

      Does the User have a sufficient role to create?

    • Clean a data source object to conform to a specific provided schema.

      Parameters

      • Optionaldata: object = {}

        Provided model data that requires cleaning

      • Optionaloptions: DataModelCleaningOptions = {}

        Options that configure how data cleaning is performed

      • Optional_state: Partial<data.types.DataModelUpdateState> = {}

        Internal options used during cleaning recursion

      Returns object

      Cleaned data which is suitable for validation and usage

    • Present a Dialog form to create a new Document of this type. Choose a name and a type from a select menu of types.

      Parameters

      • data: object = {}

        Document creation data

      • OptionalcreateOptions: DatabaseCreateOperation = {}

        Document creation options.

      • Optionaloptions: {
            context?: object;
            folders?: { id: string; name: string }[];
            template?: string;
            types?: string[];
        } = {}

        Options forwarded to DialogV2.prompt

        • Optionalcontext?: object

          Additional render context to provide to the template.

        • Optionalfolders?: { id: string; name: string }[]

          Available folders in which the new Document can be place

        • Optionaltemplate?: string

          A template to use for the dialog contents instead of the default.

        • Optionaltypes?: string[]

          A restriction of the selectable sub-types of the Dialog.

      • OptionalrenderOptions: ApplicationRenderOptions = {}

        Options to forward to the document sheet's render call.

      Returns Promise<Document<object, DocumentConstructionContext> | null>

      A Promise which resolves to the created Document, or null if the dialog was closed.

    • Create multiple Documents using provided input data. Data is provided as an array of objects where each individual object becomes one new Document.

      Parameters

      Returns Promise<Document<object, DocumentConstructionContext>[]>

      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);
      const actor = game.actors.getName("Tim");
      const data = [{name: "Sword", type: "weapon"}, {name: "Breastplate", type: "equipment"}];
      const created = await Item.implementation.createDocuments(data, {parent: actor});
      const data = [{name: "Compendium Actor", type: "character", img: "path/to/profile.jpg"}];
      const created = await Actor.implementation.createDocuments(data, {pack: "mymodule.mypack"});
    • Gets the default new name for a Document

      Parameters

      • context: {
            pack?: string | null;
            parent?: Document<object, DocumentConstructionContext> | null;
            type?: string;
        } = {}

        The context for which to create the Document name.

        • Optionalpack?: string | null

          A compendium pack within which the Document should be created

        • Optionalparent?: Document<object, DocumentConstructionContext> | null

          A parent document within which the created Document should belong

        • Optionaltype?: string

          The sub-type of the document

      Returns string

    • Define 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

      Returns DataSchema

      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;
      }
      }
    • Delete 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.

      Parameters

      • ids: string[] = []

        An array of string ids for the documents to be deleted

      • Optionaloperation: Partial<Omit<DatabaseDeleteOperation, "ids">> = {}

        Parameters of the database deletion operation

      Returns Promise<Document<object, DocumentConstructionContext>[]>

      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]);
      const tim = game.actors.getName("Tim");
      const sword = tim.items.getName("Sword");
      const shield = tim.items.getName("Shield");
      const deleted = await Item.implementation.deleteDocuments([sword.id, shield.id], parent: actor});
      const actor = await pack.getDocument(documentId);
      const deleted = await Actor.implementation.deleteDocuments([actor.id], {pack: "mymodule.mypack"});
    • A helper function to handle obtaining the relevant Document from dropped data provided via a DataTransfer event. The dropped data could have:

      1. A data object explicitly provided
      2. A UUID

      Parameters

      • data: object

        The data object extracted from a DataTransfer event

      Returns Promise<Document<object, DocumentConstructionContext>>

      The resolved Document

      If a Document could not be retrieved from the provided data.

    • Create 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!

      Parameters

      Returns Promise<Document<object, DocumentConstructionContext>>

    • A compatibility method that returns the appropriate name of an embedded collection within this Document.

      Parameters

      • name: string

        An existing collection name or a document name.

      Returns string | null

      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.

      Actor.implementation.getCollectionName("items");
      // returns "items"
      Actor.implementation.getCollectionName("Item");
      // returns "items"
    • Migrate candidate source data for this DataModel which may require initial cleaning or transformations.

      Parameters

      • source: object

        Candidate source data for the module, before further cleaning

      • Optionaloptions: Readonly<DataModelCleaningOptions>

        Additional options for how the field is cleaned

      • Optional_state: data.types.DataModelUpdateState

        Internal state variables which are used during recursion

      Returns object

      Migrated source data, ready for further cleaning

    • Wrap data migration in a try/catch which attempts it safely.

      Parameters

      • source: object

        Candidate source data for the module, before further cleaning

      • Optionaloptions: Readonly<DataModelCleaningOptions> = {}

        Additional options for how the field is cleaned

      Returns object

      Migrated source data, ready for further cleaning

    • Take 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.

      Parameters

      • data: object

        Data which matches the current schema

      • Optionaloptions: { embedded?: boolean } = {}

        Additional shimming options

        • Optionalembedded?: boolean

          Apply shims to embedded models?

      Returns object

      Data with added backwards-compatible properties, which is the same object as the data argument

    • Update multiple Document instances using provided differential data. Data is provided as an array of objects where each individual object updates one existing Document.

      Parameters

      • updates: object[] = []

        An array of differential data objects, each used to update a single Document

      • Optionaloperation: Partial<Omit<DatabaseUpdateOperation, "updates">> = {}

        Parameters of the database update operation

      Returns Promise<Document<object, DocumentConstructionContext>[]>

      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);
      const actor = game.actors.getName("Timothy");
      const updates = [{_id: sword.id, name: "Magic Sword"}, {_id: shield.id, name: "Magic Shield"}];
      const updated = await Item.implementation.updateDocuments(updates, {parent: actor});
      const actor = await pack.getDocument(documentId);
      const updated = await Actor.implementation.updateDocuments([{_id: actor.id, name: "New Name"}],
      {pack: "mymodule.mypack"});
    • Evaluate 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.

      Parameters

      • data: object

        Candidate data for the model

      Returns void

      An error if a validation failure is detected

    • Protected

      Apply final custom model-specific cleaning rules after data schema fields are cleaned. Subclass models can implement this function as an ideal place to apply custom imputation or cleaning. Cleaning must be done in-place rather than returning a different object.

      Parameters

      Returns object

      The original data object, with cleaning performed inplace

    • Protected

      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.

      Parameters

      Returns Promise<boolean | void>

      Return false to cancel the creation operation entirely

    • Protected

      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.

      Parameters

      Returns Promise<boolean | void>

      Return false to cancel the deletion operation entirely

    • Protected

      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.

      Parameters

      Returns Promise<boolean | void>

      Return false to cancel the update operation entirely