66 lines
2.1 KiB
PHP
66 lines
2.1 KiB
PHP
<?php
|
|
|
|
// Select2 source of LIMS values for a fixed field. Returns {results:[{id,text}]}.
|
|
// Params: field_key (required), template_id (required, drives client-dependent lists),
|
|
// q (search), id (resolve a single value for preselect), limit.
|
|
|
|
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
|
require_once __DIR__ . '/class/db-functions.php';
|
|
require_once __DIR__ . '/class/binding-functions.php';
|
|
include dirname(__DIR__) . '/../extra/auth.php';
|
|
|
|
header('Content-Type: application/json');
|
|
ini_set('display_errors', '0');
|
|
error_reporting(E_ALL);
|
|
|
|
if (!Auth::check()) {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Unauthorized']);
|
|
exit;
|
|
}
|
|
|
|
$fieldKey = trim($_GET['field_key'] ?? '');
|
|
$templateId = intval($_GET['template_id'] ?? 0);
|
|
$q = mb_strtolower(trim($_GET['q'] ?? ''));
|
|
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
|
|
$rawLimit = intval($_GET['limit'] ?? 30);
|
|
$limit = $rawLimit <= 0 ? 0 : max(1, min(500, $rawLimit));
|
|
|
|
if ($fieldKey === '' || !binding_fixed_is_list($fieldKey)) {
|
|
echo json_encode(['results' => []]);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$pdo = DBHandlerSelect::getInstance()->getConnection();
|
|
$values = binding_get_fixed_values($pdo, $fieldKey, $templateId);
|
|
|
|
if ($id !== null) {
|
|
foreach ($values as $v) {
|
|
if ((int) $v['id'] === $id) {
|
|
echo json_encode(['results' => [['id' => $v['id'], 'text' => $v['text']]]]);
|
|
exit;
|
|
}
|
|
}
|
|
echo json_encode(['results' => []]);
|
|
exit;
|
|
}
|
|
|
|
$results = [];
|
|
foreach ($values as $v) {
|
|
$text = (string) $v['text'];
|
|
if ($q === '' || mb_strpos(mb_strtolower($text), $q) !== false) {
|
|
$results[] = ['id' => $v['id'], 'text' => $text];
|
|
if ($limit > 0 && count($results) >= $limit) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
usort($results, fn($a, $b) => strcasecmp($a['text'], $b['text']));
|
|
echo json_encode(['results' => $results]);
|
|
} catch (Exception $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['error' => $e->getMessage()]);
|
|
}
|