ProjectModel
This class represents a global project of your Project plan or Gantt - a central place for all data.
It holds and links the stores used by Gantt:
The project has an internal scheduling engine to calculate dates, durations and such. It is also responsible for handling references between models, for example to link a task to a resource (via an assignment). These operations are asynchronous, a fact that is hidden when working in the Gantt UI but which you must know about when performing data level operations.
Task Scheduling
Without constraints in the dataset there is nothing pinning the tasks to their date, and they will be rescheduled as soon as possible, i.e. at the project start date. To avoid this, simply set autoSetConstraints to true on the ProjectModel config object. This ensures tasks remain on their specified start dates, providing a more accurate project timeline.
project : {
autoSetContraints : true
}
With that, if you use the following data, it will show the tasks at their startDate.
[{
"id" : 1,
"name" : "Project Initiation",
"percentDone" : 100,
"duration" : 5,
"startDate" : "2024-06-03"
},
{
"id" : 2,
"name" : "Requirements Gathering",
"percentDone" : 80,
"duration" : 10,
"startDate" : "2024-06-10"
},
{
"id" : 3,
"name" : "Design Phase",
"percentDone" : 60,
"duration" : 15,
"startDate" : "2024-06-24"
}]
More about this topic can be found in the Gantt scheduling guide
To see it in action, check out the auto constraintsdemo.
When there is a change to data that requires something else to be recalculated, the project schedules a calculation (a commit) which happens moments later. It is also possible to trigger these calculations directly. This flow illustrates the process:
- Something changes which requires the project to recalculate, for example adding a new task:
const [task] = project.taskStore.add({ startDate, endDate });
- A recalculation is scheduled, thus:
task.duration; // <- Not yet calculated
- Calculate now instead of waiting for the scheduled calculation
await project.commitAsync();
task.duration; // <- Now available
Please refer to this guide for more information.
Built-in CrudManager
Gantt's project has a CrudManager built-in. Using it is the recommended way of syncing data between Gantt and a backend. Example usage:
const gantt = new Gantt({
project : {
// Configure urls used by the built-in CrudManager
transport : {
load : {
url : 'php/load.php'
},
sync : {
url : 'php/sync.php'
}
}
}
});
// Load data from the backend
gantt.project.load()
URLs may also be specified using shortcut configs:
const gantt = new Gantt({
project : {
loadUrl : 'php/load.php'
syncUrl : 'php/sync.php'
}
});
gantt.project.load()
For more information on CrudManager, see Schedulers docs on CrudManager. For a detailed description of the protocol used by CrudManager, please see the Crud manager guide
You can access the current Project data changes anytime using the changes property.
Working with inline data
The project provides an inlineData getter/setter that can be used to manage data from all Project stores at once. Populating the stores this way can be useful if you do not want to use the CrudManager for server communication but instead load data using Axios or similar.
Getting data
const data = gantt.project.inlineData;
// use the data in your application
Setting data
// Get data from server manually
const data = await axios.get('/project?id=12345');
// Feed it to the project
gantt.project.inlineData = data;
See also loadInlineData
Getting changed records
You can access the changes in the current Project dataset anytime using the changes property. It returns an object with all changes:
const changes = project.changes;
console.log(changes);
The changes object has the following structure:
{
tasks : {
updated : [{
name : 'My task',
id : 12
}]
},
assignments : {
added : [{
event : 12,
resource : 7,
units : 100,
$PhantomId : 'abc123'
}]
}
};
Monitoring data changes
While it is possible to listen for data changes on the projects individual stores, it is sometimes more convenient to have a centralized place to handle all data changes. By listening for the change event your code gets notified when data in any of the stores changes. Useful for example to keep an external data model up to date:
const gantt = new Gantt({
project: {
listeners : {
change({ store, action, records }) {
const { $name } = store.constructor;
if (action === 'add') {
externalDataModel.add($name, records);
}
if (action === 'remove') {
externalDataModel.remove($name, records);
}
}
}
}
});
Processing the data loaded from the server
If you want to process the data received from the server after loading, you can use the beforeLoadApply or beforeSyncApply events:
const gantt = new Gantt({
project: {
listeners : {
beforeLoadApply({ response }) {
// do something with load-response object before it is provided to all the project stores
}
}
}
});
Built-in StateTrackingManager
The project also has a built-in StateTrackingManager (STM for short), that handles undo/redo for the project stores (additional stores can also be added). By default, it is only used while editing tasks using the task editor, the editor updates tasks live and uses STM to rollback changes if canceled. But you can enable it to track all project store changes:
// Enable automatic transaction creation and start recording
project.stm.autoRecord = true;
project.stm.enable();
// Undo a transaction
project.stm.undo();
// Redo
project.stm.redo();
Check out the undoredo demo to see it in action.
Fields
Fields belong to a Model class and define the Model data structure-
trueto enable automatic % done calculation for summary tasks,falseto disable it. -
When
true(default) adjacent or overlapping task segments get merged automatically. -
Deprecated:
Please use autoPostponeConflicts field name.
If this field is set to
truescheduling conflicts will not show the conflict resolution popup but instead will be saved into tasks postponedConflict field. -
The project calendar.
-
The source of the calendar for dependencies (the calendar used for taking dependencies lag into account). Possible values are:
ToEvent- successor calendar will be used (default);FromEvent- predecessor calendar will be used;Project- the project calendar will be used.AllWorking- the project 24/7 elapsed calendar will be used.
-
Description of the project
-
Name of the project
-
Specifies how started tasks are scheduled. Possible values are:
Auto- (default) tasks are scheduled regardless of whether they are started or notManual- started tasks preserve their current positions ignoring their dependencies The rationale behind this is a started task implies its start date is already established and thus should not be calculated dynamically.
-
Start expanded or not (only valid for tree data)
-
This is a read-only field provided in server synchronization packets to specify which position the node takes in the parent's ordered children array. This index is set on load and gets updated on reordering nodes in tree. Sorting and filtering have no effect on it.
-
Deprecated:
This field has been deprecated. Please read the guide to find out if your app needs to use the new isFullyLoaded field.
This field is added to the class at runtime when the Store is configured with lazyLoad. The number specified should reflect the total amount of children of a parent node, including nested descendants.
Configs
Configs are options you supply in a configuration object when creating an instance of this class-
Deprecated:
The flag is added as a temporary solution and is going to be removed in a next release. Please contact us if you need that old behavior.
Enables backward compatible conflicts postponing logic covering only conflicts between a task constraint and its incoming dependencies.
-
The project calendar.
-
Set to
trueto reset the undo/redo queues of the internal StateTrackingManager after the Project has loaded. Defaults tofalse -
Configuration options to provide to the STM manager
Has a corresponding runtime stm property.
-
trueto automatically persist store changes after edits are made in any of the stores monitored. Please note that sync request will not be invoked immediately but only after autoSyncTimeout interval. -
The timeout in milliseconds to wait before persisting changes to the server. Used when autoSync is set to
true. -
Configuration of the JSON encoder used by the Crud Manager.
- requestData : Object
Static data to send with the data request.
new CrudManager({ // add static "foo" property to all requests data encoder : { requestData : { foo : 'Bar' } }, ... });The above snippet will result adding "foo" property to all requests data:
{ "requestId" : 756, "type" : "load", "foo" : "Bar", "stores" : [ ...
- requestData : Object
-
Specify as
trueto force sync requests to be sent when callingsync(), even if there are no local changes. Useful in a polling scenario, to keep client up to date with the backend.Has a corresponding runtime forceSync property.
-
Set to
trueto make STM ignore changes coming from the backend. This will allow user to only undo redo local changes.Has a corresponding runtime ignoreRemoteChangesInSTM property.
-
Field name to be used to transfer a phantom record identifier.
-
Field name to be used to transfer a phantom parent record identifier.
-
Trueto reset identifiers (defined byidFieldconfig) of phantom records before submitting them to the server. -
When
truetreats parsed responses withoutsuccessproperty as successful. In this mode a parsed response is treated as invalid if it has explicitly setsuccess : false. -
If
true, project changes API will also report project model changes: start/end date, calendar, effort, duration, etc.Has a corresponding runtime trackProjectModelChanges property.
-
When
trueforces the CRUD manager to process responses depending on theirtypeattribute. Soloadrequest may be responded withsyncresponse for example. Can be used for smart server logic allowing the server to decide when it's better to respond with a complete data set (loadresponse) or it's enough to return just a delta (syncresponse). -
trueto write all fields from the record to the server. If set tofalseit will only send the fields that were modified. Note that any fields that have persist set tofalsewill still be ignored and fields having alwaysWrite set totruewill always be included. -
Internal listeners, that cannot be removed by the user.
-
Data use to fill the assignmentStore. Should be an array of AssignmentModels or its configuration objects.
Has a corresponding runtime assignments property.
-
Data use to fill the calendarManagerStore. Should be a CalendarModel array or its configuration objects.
Has a corresponding runtime calendars property.
-
Data use to fill the dependencyStore. Should be an array of DependencyModels or its configuration objects.
Has a corresponding runtime dependencies property.
-
Data use to fill the resourceStore. Should be an array of ResourceModels or its configuration objects.
Has a corresponding runtime resources property.
-
Data use to fill the taskStore. Should be an array of TaskModels or its configuration objects.
Has a corresponding runtime tasks property.
-
Data use to fill the timeRangeStore. Should be an array of TimeRangeModels or its configuration objects.
Has a corresponding runtime timeRanges property.
-
The number of Resource records each page should contain, when using remotePaging
-
Deprecated:
6.3.0 Use assignments instead
The initial data, to fill the assignmentStore with. Should be an array of AssignmentModels or configuration objects.
-
Deprecated:
6.3.0 Use calendars instead
The initial data, to fill the calendarManagerStore with. Should be an array of CalendarModels or configuration objects.
-
Deprecated:
6.3.0 Use dependencies instead
The initial data, to fill the dependencyStore with. Should be an array of DependencyModels or configuration objects.
-
Deprecated:
6.3.0 This config will be removed when the eventsData, resourcesData etc. properties are removed in a future release.
Whether to include legacy data properties in the JSON / inlineData output. The legacy data properties are the
xxData(eventsData,resourcesDataetc.) properties that are deprecated and will be removed in the future.Has a corresponding runtime includeLegacyDataProperties property.
-
Deprecated:
6.3.0 Use resources instead
The initial data, to fill the resourceStore with. Should be an array of ResourceModels or configuration objects.
-
Deprecated:
6.3.0 Use tasks instead
The initial data, to fill the taskStore with. Should be an array of TaskModels or configuration objects.
-
Deprecated:
6.3.0 Use timeRanges instead
The initial data, to fill the timeRangeStore with. Should be an array of TimeRangeModels or configuration objects.
-
The constructor of the assignment model class, to be used in the project. Will be set as the modelClass property of the assignmentStore
-
An AssignmentStore instance or a config object.
Has a corresponding runtime assignmentStore property.
-
The constructor to create a dependency store instance with. Should be a class, subclassing the AssignmentStore
-
A CalendarManagerStore instance or a config object.
Has a corresponding runtime calendarManagerStore property.
-
The constructor to create a calendar store instance with. Should be a class, subclassing the CalendarManagerStore
-
The constructor of the calendar model class, to be used in the project. Will be set as the modelClass property of the calendarManagerStore
-
The constructor of the dependency model class, to be used in the project. Will be set as the modelClass property of the dependencyStore
-
A DependencyStore instance or a config object.
Has a corresponding runtime dependencyStore property.
-
The constructor to create a dependency store instance with. Should be a class, subclassing the DependencyStore
-
A TaskStore instance or a config object.
Has a corresponding runtime eventStore property.
-
The constructor of the resource model class, to be used in the project. Will be set as the modelClass property of the resourceStore
-
A ResourceStore instance or a config object.
Has a corresponding runtime resourceStore property.
-
The constructor to create a dependency store instance with. Should be a class, subclassing the ResourceStore
-
The constructor of the event model class, to be used in the project. Will be set as the modelClass property of the eventStore
-
An alias for the eventStore.
Has a corresponding runtime taskStore property.
-
The constructor to create an task store instance with. Should be a class, subclassing the TaskStore
-
Store that holds time ranges - instances of TimeRangeModel for the TimeRanges feature. A store will be automatically created if none is specified.
Has a corresponding runtime timeRangeStore property.
Properties
Properties are getters/setters or publicly accessible variables on this class-
Identifies an object as an instance of AbstractCrudManagerMixin class, or subclass thereof.
-
Identifies an object as an instance of AbstractCrudManagerValidation class, or subclass thereof.
-
Identifies an object as an instance of AjaxTransport class, or subclass thereof.
-
Identifies an object as an instance of Delayable class, or subclass thereof.
-
Identifies an object as an instance of Events class, or subclass thereof.
-
Identifies an object as an instance of JsonEncoder class, or subclass thereof.
-
Identifies an object as an instance of LazyLoadCrudManager class, or subclass thereof.
-
Identifies an object as an instance of ModelLink class, or subclass thereof.
-
Identifies an object as an instance of ModelStm class, or subclass thereof.
-
Identifies an object as an instance of ProjectChangeHandlerMixin class, or subclass thereof.
-
Identifies an object as an instance of ProjectCrudManager class, or subclass thereof.
-
Identifies an object as an instance of ProjectModel class, or subclass thereof.
-
Identifies an object as an instance of ProjectModelCommon class, or subclass thereof.
-
Identifies an object as an instance of ProjectModelTimeZoneMixin class, or subclass thereof.
-
Identifies an object as an instance of ProjectRevisionHandlerMixin class, or subclass thereof.
-
Identifies an object as an instance of TreeNode class, or subclass thereof.
-
A class property getter for the default values of internal properties for this class.
-
An array containing all the defined fields for this Model class. This will include all superclass's defined fields.
-
An object containing all the defined fields for this Model class. This will include all superclass's defined fields through its prototype chain. So be aware that
Object.keysandObject.entrieswill only access this class's defined fields. -
The data source for the id field which provides the ID of instances of this Model.
-
Returns the data from all CrudManager
crudStoresin a format that can be consumed byinlineData. -
Enables/disables the calculation progress notifications.
Has a corresponding enableProgressNotifications config.
-
State tracking manager instance the project relies on
Has a corresponding stm config.
-
An empty array that can be used as a default value.
-
An empty object that can be used as a default value.
-
A list of registered stores whose server communication will be collected into a single batch. Each store is represented by a store descriptor.
Has a corresponding crudStores config.
-
Specify as
trueto force sync requests to be sent when callingsync(), even if there are no local changes. Useful in a polling scenario, to keep client up to date with the backend.Has a corresponding forceSync config.
-
Set to
trueto make STM ignore changes coming from the backend. This will allow user to only undo redo local changes.Has a corresponding ignoreRemoteChangesInSTM config.
-
Returns
trueif changes tracking is suspended -
Returns true if the crud manager is currently loading data
-
Returns true if the crud manager is currently syncing data
-
Generates unique request identifier.
-
An array of stores presenting an alternative sync responses apply order. Each store is represented by a store descriptor.
Has a corresponding syncApplySequence config.
-
If
true, project changes API will also report project model changes: start/end date, calendar, effort, duration, etc.Has a corresponding trackProjectModelChanges config.
-
Identifies an object as an instance of Model class, or subclass thereof.
-
Identifies an object as an instance of ProjectModel class, or subclass thereof.
-
For copied records, this property links to the original model instance from which it was copied.
-
True if this Model is currently batching its changes.
-
True if this models changes are currently being committed.
-
True if this model has any uncommitted changes.
-
Check if record has valid data. Default implementation returns true, override in your model to do actual validation.
-
Get a map of the modified fields in form of an object. The field´s dataSource is used as the property name in the returned object. The record's id is included unless its persist config is
false. -
Get a map of the modified data fields along with any alwaysWrite fields, in form of an object. The field´s dataSource is used as the property name in the returned object. Used internally by AjaxStore / CrudManager when sending updates.
-
Returns data for allpersistable fields in form of an object, using dataSource if present.
-
Returns a map of the modified persistable fields
-
Returns the string value for display purposes of an instance of this Model class. Needs to be overridden in subclasses.
-
When called on a group header row returns list of records in that group. Returns
undefinedotherwise. -
Returns true for a group header record
-
Gets the records internalId. It is assigned during creation, guaranteed to be globally unique among models.
-
Returns true if the record is new and has not been persisted (and received a proper id).
-
If set to
true, or a config object, this makes the CrudManager load records only when needed. When a record or a date range that is not already loaded is requested, a load request will be made to the specified URL. More more details about lazy loading, see the guideHas a corresponding lazyLoad config.
-
Deprecated:
6.3.0 This config will be removed when the eventsData, resourcesData etc. properties are removed in a future release.
Whether to include legacy data properties in the JSON / inlineData output. The legacy data properties are the
xxData(eventsData,resourcesDataetc.) properties that are deprecated and will be removed in the future.Has a corresponding includeLegacyDataProperties config.
-
Returns a copy of the full configuration which was used to configure this object.
-
This property is set to
truebefore theconstructorreturns. -
This property is set to
trueon entry to the destroy method. It remains on the objects after returning fromdestroy(). If isDestroyed istrue, this property will also betrue, so there is no need to test for both (for example,comp.isDestroying || comp.isDestroyed). -
Are other records linked to this record?
-
Is this record linked to another record?
-
Get the original record this record is linked to.
-
Get links to this record.
-
Get the first store that this model is assigned to.
-
This yields
trueif this record is eligible for syncing with the server. It can yieldfalseif the record is in the middle of a batched update, or if it is a tentative record yet to be confirmed as a new addition. -
Returns true if this record is not part of any store.
-
Retrieve all children, excluding filtered out nodes (by traversing sub nodes)
-
Retrieve all children, including filtered out nodes (by traversing sub nodes)
-
Depth in the tree at which this node exists. First visual level of nodes are at level 0, their direct children at level 1 and so on.
-
Count all children (including sub-children) for a node (in its `firstStore´)
-
Get the first child of this node
-
Returns index path to this node. This is the index of each node in the node path starting from the topmost parent. (only relevant when its part of a tree store).
-
Is a leaf node in a tree structure?
-
Returns true for parent nodes with children loaded (there might still be no children)
-
Is a parent node in a tree structure?
-
Returns
trueif this node is the root of the tree -
Get the last child of this node
-
Get the next sibling of this node
-
This is a read-only property providing access to the parent node.
-
Get the previous sibling of this node
-
Returns count of all preceding sibling nodes (including their children).
-
Array of tree nodes without any filter applied. On first filter, will take order from sorted
children, but is not thereafter kept in sorted order, so order should not be relied upon. -
Count visible (expanded) children (including sub-children) for a node (in its
firstStore) -
Returns values of the persistable tree-defining fields: parentId, orderedParentIndex, and parentIndex or sparseIndex. parentIndex is omitted when sparseIndex is used.
Functions
Functions are methods available for calling on the class-
This optional class method is called when a class is mixed in using the mixin() method.
-
Registers this class type with its Factory
-
Makes getters and setters for related records. Populates a Model#relation array with the relations, to allow it to be modified later when assigning stores.
-
Accepts all changes in all stores, resets the modification tracking:
- Clears change tracking for all records
- Clears added
- Clears modified
- Clears removed Leaves the store in an "unmodified" state.
-
Reverts all changes in all stores and re-inserts any records that were removed locally. Any new uncommitted records will be removed.
-
Suspends automatic sync upon store changes. Can be called multiple times (it uses an internal counter).
-
Suspends hasChanges and noChanges events.
-
cancelBatch( ) Model
Cancels current batch operation. Any changes during the batch are discarded.
-
Internal function used to hook destroy() calls when using thisObj
-
Internal function used restore hooked destroy() calls when using thisObj
-
Auto detaches listeners registered from start, if set as detachable
-
Internal function used to run a callback function after an event is triggered
-
Removes all listeners registered to this object by the application.
-
Called from insertChild to notify StateTrackingManager about children insertion. Provides it with all necessary context information collected in beforeInsertChild required to undo/redo the action.
-
Called from removeChild to notify StateTrackingManager about children removing. Provides it with all necessary context information collected in beforeRemoveChild required to undo/redo the action.
-
Called during creation to also turn any children into Models joined to the same stores as this model
-
Initializes model relations. Called from store when adding a record.
-
Causes the scheduling engine to re-evaluate the task data and all associated data and constraints and apply necessary changes.
-
Suspend propagation processing. When propagation is suspended, calls to propagate do not proceed, instead a propagate call is deferred until a matching resumePropagate is called.
-
Removes all records from the rootNode