Last updated December 20, 2007. Created by fago on December 20, 2007.
Log in to edit this page.
The states module comes together with workflow-ng. It provides a flexible state machine API for other modules. Modules can define their own state machines, which have to operate upon known entities. Currently the states module supports only nodes and users.
So you can use it, to easily track the state of a node or a user. It provides some useful conditions/actions for workflow-ng as well as views and token integration. Views integration allows one to easily build lists of nodes of a certain state.
Defining state machines
States are tracked in state machines. There may be multiple state machines on the same entity. Modules can define state machines by using hook_states():
<?php
/**
* Implementation of hook_states
* Use a state machine to track toggled links
*/
function myModule_states() {
$machines = array();
$machines['myModule_machine'] = array(
'#label' => t('MyModules Content State'),
'#entity' => 'node',
'#types' => array('page', 'story'), //optional
'#states' => array('draft', 'needs_review', 'needs_work', 'published'),
'#init_state' => 'draft' //optional
);
}
return $machines;
}?>So this creates a new state machine with the machine readable state machine name "myModule_machine". When the node is created, but no state machine gets set, the states module will set the init state 'draft'.
Setting new states
This example tracks the state of a node, for users it works the same way.
Two useful API functions are:
states_machine_set_state($entity, $machine_name, $new_state)
Sets the state of the given machine for this entity to the given new state. It will generate a new event for the state change and return the modified entity object, if the state was valid and so the operation successful, otherwise NULL is returned.
states_entity_get_machine_state($entity, $machine_name)
This may be used to get the state of a machine. You can also read from $entity->states['Your_Machine_Name'], but using this function is more reliable, as it:
* Checks whether the entitiy is fully loaded. If not, the machine state will be loaded for you.
* also works with state machines, that define a custom attribute name that is different than the machine name (see #attribute_name)
Then you can use states_entity_set_machine_state($entity, $machine_name, $new_state), if you want to set the state of a machine without writing directly to the database, e.g. you can let node_save() or user_save() take over this.