I never noticed it, but:
- If I create a node containing a reference and set the reference field to null, the field is still set as an
EntityReferenceFieldItemList
, e.g. the following code
echo "Creating a node with ref_field=null", PHP_EOL ;
$node = Node::create([
'type' => 'my_type',
'uid' => \Drupal::currentUser()->id(),
'title' => "title",
'field_ref_field' => null,
]) ;
// $node->field_ref_field = null ;
$node->save() ;
echo "Ref field is a " . gettype($node->field_ref_field) . ", and more specifically: " . get_class($node->field_ref_field), PHP_EOL ;
echo "Its id is ", $node->id(), PHP_EOL ;
produces on output
Creating a node with ref_field=null
Ref field is a object, and more specifically: Drupal\Core\Field\EntityReferenceFieldItemList
Its id is 933461
The same result occurs if I set ref_field to null
after node creation, uncommenting the line that follows.
$node = Node::load(933461) ;
echo "Ref field is a " . gettype($evento->field_seduta), PHP_EOL ;
the result is
Field seduta is a NULL
As a consequence of this behaviour, to check if a reference field is valid I have either to check both the field itself and its target_id for null
ness,
if (! $node->field_ref_field || ! $node->field_ref_field->target_id)
that is annoying, or to make sure that a certain code fragment is reached after node creation or node loading, that is fragile.
Am I missing something? What is the reason of this strange behaviour?