EntityReference.php in Conditional Fields 4.x
File
src/Plugin/conditional_fields/handler/EntityReference.php
View source
<?php
namespace Drupal\conditional_fields\Plugin\conditional_fields\handler;
use Drupal\conditional_fields\ConditionalFieldsHandlerBase;
use Drupal\conditional_fields\ConditionalFieldsInterface;
use Drupal\node\Entity\Node;
class EntityReference extends ConditionalFieldsHandlerBase {
public function statesHandler($field, $field_info, $options) {
$state = [];
$values_set = $options['values_set'];
switch ($values_set) {
case ConditionalFieldsInterface::CONDITIONAL_FIELDS_DEPENDENCY_VALUES_WIDGET:
$value_form = $this
->getWidgetValue($options['value_form']);
if (empty($value_form)) {
break;
}
if ($options['field_cardinality'] == 1) {
$node = Node::load($value_form[0]['target_id']);
if ($node instanceof Node) {
$state[$options['state']][$options['selector']] = $this
->getAutocompleteSuggestions($node);
}
}
else {
$ids = array_column($value_form, 'target_id');
$nodes = Node::loadMultiple($ids);
if (!empty($nodes)) {
foreach (array_values($nodes) as $key => $node) {
$selector = str_replace('[0]', "[{$key}]", $options['selector']);
$state[$options['state']][$selector] = $this
->getAutocompleteSuggestions($node);
}
}
}
break;
default:
break;
}
return $state;
}
private function getAutocompleteSuggestions(Node $node) {
return [
[
'value' => $node
->label() . ' (' . $node
->id() . ')',
],
[
'value' => $node
->label(),
],
];
}
public function getWidgetValue(array $value_form) {
return $value_form;
}
}