DrupalDriver
DrupalDriver copied to clipboard
Allow entity reference values to be ids.
The expand function in the existing version of the D7 entity reference handler makes the assumption that the argument that is passed in will be a title string (or a name, in the case of the user). I suggest the following modification, which makes the assumption that the argument is a nid (or uid) if the $value is numeric.
I can't test the D8 version I cooked up, but I'm guessing it would look like something like the following:
/**
* {@inheritdoc}
*/
public function expand($values) {
$return = array();
$entity_type_id = $this->fieldInfo->getSetting('target_type');
$entity_definition = \Drupal::entityManager()->getDefinition($entity_type_id);
// Determine target bundle restrictions.
$target_bundle_key = NULL;
if (!$target_bundles = $this->getTargetBundles()) {
$target_bundle_key = $entity_definition->getKey('bundle');
}
foreach ($values as $value) {
if(is_numeric($value)){
$label_key = $entity_definition->getKey('id');
}
else{
$label_key = $entity_definition->getKey('label');
}
$query = \Drupal::entityQuery($entity_type_id)->condition($label_key, $value);
if ($target_bundles && $target_bundle_key) {
$query->condition($target_bundle_key, $target_bundles, 'IN');
}
if ($entities = $query->execute()) {
$return[] = array_shift($entities);
}
else {
throw new \Exception(sprintf("No entity '%s' of type '%s' exists.", $value, $entity_type_id));
}
}
return $return;
}