How do I get the property of a node object? I am trying to get the moderation_state property from a node object in Drupal8 (see attached image); however, I cannot work out how to do this.  In Drupal7 it was pretty straight forward $node-&gt;moderation_state.

How can I get this value in Drupal8 where $node is an instance of Drupal\node\Entity\Node?

I have tried:
$node->moderation_state
$node->moderation_state->value
Firstly, some background.

When you type $node-&gt;something you're getting a FieldItemListInterface. How do you know what values you can use for something? Well you can ask the entity.
$node-&gt;getFieldDefinitions()

Now you have a FieldItemListInterface you can iterate over its values, or in the case of single-value field, just its first one. So even if you're using $node-&gt;title, title is a FieldItemListInterface even though you'd only expect one item in the list.

So lets get the first value in the list. $node-&gt;something-&gt;get(0). This gives you a FieldItemInterface. From here you can access the properties of the field item. E.g. $node-&gt;title-&gt;get(0)-&gt;get('value'). Each of these is an instance of TypedDataInterface. But how do you know what you can use for value. E.g. For an entity reference field $node-&gt;some_er_field-&gt;target_id is valid but $node-&gt;some_er_field-&gt;value is not. Well you can ask the FieldItemInterface like so $node-&gt;title-&gt;get(0)-&gt;getProperties(). Or alternatively, you can know the data-type of the field and inspect its propertyDefinitions method. E.g. in the case of moderation_state field, it uses an Entity Reference field to track the reference to the moderation state config entity. So that means each FieldItemInterface is actually an EntityReferenceItem and you can check its ::propertyDefinitions() method to see what properties it defines.

So now you have a TypedDataInterface object, how do you get it's value? Well you use its ::getValue() method.

But wait why does $node-&gt;title-&gt;value work - I don't have to write $node-&gt;title-&gt;get(0)-&gt;get('value')-&gt;getValue() - well thats because we're using PHP magic methods on FieldItemListInterface and FieldItemInterface such that $node-&gt;title-&gt;value calls $node-&gt;title-&gt;get(0)-&gt;get('value')-&gt;getValue() for you.

So in summary:


$node-&gt;moderation_state-&gt;get(0)-&gt;get('target_id')-&gt;getValue() will give you the moderation state config entity's ID.
$node-&gt;moderation_state-&gt;get(0)-&gt;get('entity')-&gt;getValue() will give you the ModerationState config entity, so you can use its methods direct - like ::isPublished() and ::label().
$node-&gt;moderation_state-&gt;target_id and $node-&gt;moderation_state-&gt;entity would achieve the same thing respectively.


I did a lightning talk for my colleagues on this, if you're interested the slides are here unfortunately the recording didn't work.