*/
declare(strict_types=1);
namespace oat\tao\helpers\form\elements\xhtml;
use oat\tao\helpers\form\elements\ElementValue;
use oat\tao\helpers\form\elements\AbstractSearchElement;
use tao_helpers_Display;
use tao_helpers_form_elements_xhtml_Hidden;
use tao_helpers_Uri;
abstract class AbstractXhtmlSearchElement extends AbstractSearchElement
{
use XhtmlRenderingTrait;
protected $attributes = [
'class' => 'form_radlst',
];
/**
* @inheritDoc
*/
public function setValue($value): void
{
$this->addValue($value);
}
/**
* @inheritDoc
*/
public function render(): string
{
if (!empty($this->unit)) {
$this->addClass('has-unit');
$label = sprintf(
'',
'unit',
$this->name,
tao_helpers_Display::htmlize($this->unit)
);
}
$html = [];
$html[] = $this->renderLabel();
$html[] = sprintf(
'',
$this->createClientCode()
);
$html[] = sprintf(
'
%s
',
$this->renderAttributes(),
$this->createHiddenInput()->render() . ($label ?? '')
);
return implode('', $html);
}
abstract protected function isMultiValue(): bool;
private function createClientCode(): string
{
$searchUrl = tao_helpers_Uri::url('get', 'PropertyValues', 'tao');
$baseVariables = $this->createBaseClientVariables();
$initSelectionValues = $this->createInitSelectionValues();
if ($this->isMultiValue()) {
$multipleValue = 'true';
} else {
$initSelectionValues = reset($initSelectionValues);
$multipleValue = 'false';
}
$initSelection = json_encode($initSelectionValues);
return <<name');
var normalizeItem = function (item) { return { id: item.uri, text: item.label } };
var normalizeResponse = function (data) { return { results: data.data.map(normalizeItem) } };
var getCurrentValues = function () { return \$input.val().split('$delimiter') };
var getParentListValues = function () {
var primaryPropUri = \$input.parent().data('depends-on-property');
return primaryPropUri ? $('#' + primaryPropUri).val().split(',') : '';
}
var createRequestData = function (term) {
return {
propertyUri: '$this->name',
subject: term,
exclude: getCurrentValues(),
parentListValues: getParentListValues()
}
};
javascript;
}
private function createInitSelectionValues(): array
{
$result = [];
foreach ($this->getRawValue() as $value) {
$result[] = [
'id' => tao_helpers_Uri::encode($value->getUri()),
'text' => $value->getLabel(),
];
}
return $result;
}
private function createHiddenInput(): tao_helpers_form_elements_xhtml_Hidden
{
$input = new tao_helpers_form_elements_xhtml_Hidden($this->name);
$uris = array_map(
static function (ElementValue $value) {
return $value->getUri();
},
$this->getRawValue()
);
$input->setValue(implode(static::VALUE_DELIMITER, $uris));
return $input;
}
}