datafield-1.x-dev/src/Controller/JsonController.php
src/Controller/JsonController.php
<?php
namespace Drupal\datafield\Controller;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Class Json data Controller.
*
* @package Drupal\datafield\Controller
*/
class JsonController extends ControllerBase {
/**
* Constructor Json search.
*
* @param \Drupal\Core\Cache\CacheBackendInterface $staticCache
* The static cache.
* @param \Drupal\Core\Database\Connection $database
* The database.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
* The entity field manager.
* @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface $selectionManager
* The selection manager.
*/
public function __construct(protected CacheBackendInterface $staticCache, protected readonly Connection $database, protected readonly EntityFieldManagerInterface $entityFieldManager, protected SelectionPluginManagerInterface $selectionManager) {
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('cache.default'),
$container->get('database'),
$container->get('entity_field.manager'),
$container->get('plugin.manager.entity_reference_selection'),
);
}
/**
* Get taxonomies with parents.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request service.
* @param string $entity_type
* The entity type service.
* @param string $bundle
* Bundle.
* @param string $field_name
* Field name.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* Ajax to get select list.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function json(Request $request, $entity_type, $bundle, $field_name): JsonResponse {
$data = [];
$storage = $this->entityTypeManager()->getStorage($entity_type);
[$tableName] = $storage->getTableMapping()
->getAllFieldTableNames($field_name);
$q = $request->query->get('q');
$machine_name = $request->query->get('machine_name');
$fieldQuery = $field_name . '_' . $machine_name;
$bundle_fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);
$field_definition = $bundle_fields[$field_name];
$fields = array_keys($field_definition->getSetting('columns'));
$fieldNames = [];
if (!empty($fields)) {
foreach ($fields as $fieldName) {
$fieldNames[$fieldName] = $field_name . '_' . $fieldName;
}
}
$language = $this->languageManager()->getCurrentLanguage()->getId();
$query = $this->database->select($tableName, 'f');
$query->fields('f');
$query->condition('f.bundle', $bundle);
$query->condition('f.langcode', $language);
if (!empty($machine_name) && !empty($q)) {
$query->distinct(TRUE);
$query->condition('f.' . $fieldQuery, '%' . $q . '%', 'LIKE');
}
$limit = $request->query->get('limit');
if (!empty($limit) && is_numeric($limit)) {
$query->range(0, $limit);
}
$entity_id = $request->query->get('entity_id');
if (!empty($entity_id)) {
$query->condition('f.entity_id', $entity_id);
}
$result = $query->execute();
foreach ($result as $row) {
$values = [];
foreach ($fields as $fieldName) {
$values[$fieldName] = $row->{$field_name . '_' . $fieldName};
}
if (!empty($machine_name) && !empty($q)) {
$label = $row->$fieldQuery;
$value = $row->$fieldQuery;
$fill = $request->query->get('fill');
$delta = $request->query->get('delta');
if ($fill) {
$label = implode(' | ', $values);
}
$data[] = [
'value' => $value,
'label' => $label,
'data' => $values,
'field' => $field_name,
'delta' => $delta,
'name' => $machine_name,
];
}
else {
$values['delta'] = $row->delta;
if (empty($entity_id)) {
$values['entity_id'] = $row->entity_id;
}
$data[] = $values;
}
}
return new JsonResponse($data);
}
/**
* Get entity for search.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The controller request service.
* @param string $target_type
* The entity type.
* @param string $selection_handler
* The selection handler.
* @param string $selection_settings_key
* The key crypto.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* Ajax to get select list.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function fieldReference(Request $request, $target_type, $selection_handler, $selection_settings_key): JsonResponse {
$selection_settings = $this->keyValue('entity_autocomplete')->get($selection_settings_key);
$options['target_type'] = $target_type;
$separator = '';
$fields = [];
if ($selection_handler == 'views') {
$options += [
'view' => $selection_settings["view"],
'handler' => 'views',
];
$view = Views::getView($selection_settings["view"]["view_name"]);
$view->setDisplay($selection_settings["view"]["display_name"]);
$displayHandler = $view->displayHandlers->get($selection_settings["view"]["display_name"]);
$rowOptions = $displayHandler->getPlugin('row')->options;
$separator = $rowOptions["separator"];
$fields = array_keys($displayHandler->getOption('fields'));
}
else {
$options += [
'target_bundles' => $selection_settings['target_bundles'],
'handler' => 'default:' . $target_type,
];
if ($target_type == 'user') {
$options['target_bundles'] = NULL;
}
}
$handler = $this->selectionManager->getInstance($options);
$entity_labels = $handler->getReferenceableEntities();
$rows = [];
foreach ($entity_labels as $values) {
foreach ($values as $entity_id => $label) {
$row = ['id' => $entity_id];
if (!empty($separator)) {
$fieldValues = explode($separator, strip_tags($label));
foreach ($fields as $index => $fieldName) {
$row[$fieldName] = $fieldValues[$index] ?? '';
}
}
else {
$row['name'] = $label;
}
$rows[] = $row;
}
}
return new JsonResponse($rows);
}
}
