$entity->
{$this->fieldName
}->target_id =
$referenced_entity->
id();
$violations =
$entity->
{$this->fieldName
}->
validate();
$this->
assertEquals(0,
$violations->
count(), 'Validation passes.'
);
// Test an invalid reference.
$entity->
{$this->fieldName
}->target_id = 9999;
$violations =
$entity->
{$this->fieldName
}->
validate();
$this->
assertEquals(1,
$violations->
count(), 'Validation throws a violation.'
);
$this->
assertEquals(t('The referenced entity (%type: %id) does not exist.',
['%type' =>
$this->referencedEntityType, '%id' => 9999
]),
$violations[0
]->
getMessage());
// Test a non-referenceable bundle.
entity_test_create_bundle('non_referenceable', NULL,
$this->referencedEntityType
);
$referenced_entity =
$this->entityTypeManager
->
getStorage($this->referencedEntityType
) ->
create(['type' => 'non_referenceable'
]);
$referenced_entity->
save();
$entity->
{$this->fieldName
}->target_id =
$referenced_entity->
id();
$violations =
$entity->
{$this->fieldName
}->
validate();
$this->
assertEquals(1,
$violations->
count(), 'Validation throws a violation.'
);
$this->
assertEquals(t('This entity (%type: %id) cannot be referenced.',
['%type' =>
$this->referencedEntityType, '%id' =>
$referenced_entity->
id()]),
$violations[0
]->
getMessage());
} /**
* Tests the multiple target entities loader.
*/