Using Relation with Rules

The Relation module has integration with Rules, primarily to allow creating new relations. It is also possible, but slightly awkward, to fetch and manipulate relation entities with Rules.

This documentation page assumes that you are already familiar with the basic concepts in Rules – in particular with lists.

Creating relations with Rules

To create a new relation in Rules, you must first have a list of entities that should be used as endpoints in the relation. The following steps will provide you with actions to create brand new relation in your rule:

  1. Add a new variable, of the type list of any entity items. (Note that lists of specific entity types won't work!)
  2. Use the action add an item to a list to add any of the entities available to Rules to the soon-to-be end point list.
  3. Repeat step 2 until you have the end points you want.
  4. Use the action create a new entity and select a relation of the type you want.
  5. In the entity creation configuration, select the entity list as endpoints.
  6. Done!

Possible stumbling block:

  • If you want to use the relation ID (for example to create links), you must use the action save entity – and also use the force immediate saving option. This will save the relation at the end of the currently executing rule, meaning that you will need a rule set (or a chain of rules) to be able to fetch the relation ID once saved.

View a screencast about creating relations with Rules

Fetching and manipulating relations with Rules

Using Rules you can also load existing relations, and perform actions on them or their end points. However, this is complicated by the fact that you usually need a good identifier for the relation you want to fetch – such as its relation ID or the entire list of endpoints.

Assuming you have one of these, you can load a relation using one of the load entity by ID or load entity by property action, fetching the entire relation entity into your rule.

Once that is done, you can access the end point objects as a list, either by looping through the list or by using data selection and selecting (say) the first end point directly.

Possible stumbling block:

  • A possible problem is that Rules may have issues recognizing the type(s) of entities stored within the list of endpoints – which may be necessary for making Rules access field data (or even, say, node titles). You need to use components for this and use the entity type condition in the component.

Migrate Node Reference Field to Relations

The following code (Rules export) allows me to move nodes from a reference field to a relation field:

Guide maintainers

itangalo's picture