From 98690b34e58493343600855b886c7d42b0214028 Mon Sep 17 00:00:00 2001 From: shinybrad <83238715+shinybrad@users.noreply.github.com> Date: Sun, 1 Dec 2024 06:11:57 -0500 Subject: [PATCH 1/7] New translations app.php (Russian) [ci skip] --- src/translations/ru/app.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/translations/ru/app.php b/src/translations/ru/app.php index c3c79ab6800..f6436710798 100644 --- a/src/translations/ru/app.php +++ b/src/translations/ru/app.php @@ -94,7 +94,7 @@ 'All users' => 'Все пользователи', 'All' => 'Все', 'Allow Upscaling' => 'Разрешить масштабирование', - 'Allow anchors' => 'Allow anchors', + 'Allow anchors' => 'Разрешить якорные ссылки', 'Allow custom options' => 'Разрешить пользовательские параметры', 'Allow line breaks' => 'Разрешить переносы строк', 'Allow public registration' => 'Разрешить публичную регистрацию', @@ -188,7 +188,7 @@ 'Attach error logs' => 'Приложить журналы ошибок', 'Attachment' => 'Вложение', 'Audio' => 'Аудио', - 'Auth error' => 'Auth error', + 'Auth error' => 'Ошибка авторизации', 'Authentication method removed.' => 'Метод авторизации удален.', 'Authenticator App' => 'Приложение для авторизации', 'Author Group' => 'Группа авторов', @@ -294,7 +294,7 @@ 'Choose which users must use two-step verification when accessing the control panel.' => 'Выберите, какие пользователи должны проходить двухэтапную проверку подлинности для получения доступа к панели управления.', 'Choose' => 'Выбрать', 'City' => 'Город', - 'City/Town' => 'City/Town', + 'City/Town' => 'Город/Населенный пункт', 'Clear Caches' => 'Очистить кэш', 'Clear all' => 'Очистить все', 'Clear caches' => 'Очистить кэши', @@ -654,7 +654,7 @@ 'Error' => 'Ошибка', 'Error:' => 'Ошибка:', 'Everything in {edition}, plus…' => 'Все возможности версии {edition} плюс…', - 'Existing {type}' => 'Existing {type}', + 'Existing {type}' => 'Существующий {type}', 'Expand' => 'Развернуть', 'Expanded' => 'Развернуто', 'Expired' => 'Срок действия истек', @@ -910,7 +910,7 @@ 'Load this template' => 'Загрузить этот шаблон', 'Loaded Project Config Data' => 'Загруженные данные конфигурации проекта', 'Loading Plugin Store…' => 'Загрузка Plugin Store…', - 'Loading complete' => 'Loading complete', + 'Loading complete' => 'Загрузка завершена', 'Loading' => 'Загрузка', 'Local Folder' => 'Локальная папка', 'Local copies of remote images, generated thumbnails' => 'Локальные копии изображений, расположенных удаленно, сгенерированные эскизы', @@ -1083,7 +1083,7 @@ 'No' => 'Нет', 'None' => 'Нет', 'Normal' => 'Нормальный', - 'Not Related To' => 'Not Related To', + 'Not Related To' => 'Не относится к', 'Not enough memory available to perform this image operation.' => 'Недостаточно памяти для выполнения операции над этим изображением.', 'Not installed' => 'Не установлено', 'Not ready' => 'Не готово', @@ -1480,7 +1480,7 @@ 'Sign in as {user}' => 'Войти как {user}', 'Sign in unsuccessful' => 'Не удалось выполнить вход в систему', 'Sign in with a passkey' => 'Войти с ключом доступа', - 'Sign in with {name}' => 'Sign in with {name}', + 'Sign in with {name}' => 'Войти как {name}', 'Sign in' => 'Войти', 'Sign out now' => 'Выйти', 'Sign out' => 'Выйти', @@ -1680,8 +1680,8 @@ 'This can begin with an environment variable.' => 'Может начинаться с переменной среды.', 'This draft’s entry type is no longer available. You can still view it, but not apply it.' => 'Этот тип записи черновика больше не доступен. Его можно просмотреть, но нельзя применить.', 'This element is conditional' => 'Данный элемент является условным', - 'This field has a tip' => 'This field has a tip', - 'This field has a warning' => 'This field has a warning', + 'This field has a tip' => 'Это поле содержит подсказку', + 'This field has a warning' => 'Это поле содержит предупреждение', 'This field has been modified.' => 'Поле было изменено.', 'This field is conditional' => 'Данное поле является условным', 'This field is included in element cards' => 'Это поле включено в карточки элементов', @@ -1786,7 +1786,7 @@ 'Unable to fetch updates at this time.' => 'Не удалось получить обновления.', 'Unable to fetch upgrade info at this time.' => 'Не удается получить информацию об обновлении.', 'Unable to find the template “{template}”.' => 'Не удалось найти шаблон «{template}».', - 'Unable to initiate an auth request.' => 'Unable to initiate an auth request.', + 'Unable to initiate an auth request.' => 'Невозможно инициировать запрос авторизации.', 'Unauthorized' => 'Недопустимые учетные данные', 'Uncheck for {offLabel}.' => 'Снимите флажок {offLabel}.', 'Unconstrained' => 'Без ограничений', @@ -1989,7 +1989,7 @@ 'You need to be on at least {plugin} {version} before you can update to {plugin} {targetVersion}.' => 'У вас должен быть {plugin} хотя бы версии {version}, чтобы выполнить обновление до {plugin} {targetVersion}.', 'You need to reset your password, but an error was encountered when sending the password reset email.' => 'Вам необходимо сбросить пароль, однако при отправке сообщения со ссылкой сброса пароля возникла ошибка.', 'You need to reset your password. Check your email for instructions.' => 'Вам нужно сменить пароль. Проверьте свою электронную почту для получения дальнейших инструкций.', - 'You need to reset your password.' => 'You need to reset your password.', + 'You need to reset your password.' => 'Вам нужно сбросить пароль.', 'Your Email' => 'Ваш адрес электронной почты', 'Your account doesn’t have permission to access the control panel when the system is offline.' => 'Вам не разрешен доступ в панель управления, когда система работает в автономном режиме.', 'Your account doesn’t have permission to access the site when the system is offline.' => 'Вам не разрешен доступ к этому сайту, когда система работает в автономном режиме.', @@ -2120,7 +2120,7 @@ '{attribute} must be no less than {min}.' => 'Значение «{attribute}» должно быть не менее {min}.', '{attribute} must be set to a new password.' => 'Для {attribute} следует настроить новый пароль.', '{attribute} must contain “{slug}”' => '{attribute} должен содержать «{slug}»', - '{attribute} no longer allows {type} links.' => '{attribute} no longer allows {type} links.', + '{attribute} no longer allows {type} links.' => '{attribute} больше не допускает ссылки типа: {type}.', '{attribute} should contain at least {min, number} {min, plural, one{address} other{addresses}}.' => 'Атрибут {attribute} должен содержать не менее {min, number} {min, plural, one{адреса} few {адресов} many {адресов} other{адреса}}.', '{attribute} should contain at least {min, number} {min, plural, one{entry} other{entries}}.' => 'Атрибут {attribute} должен содержать не менее {min, number} {min, plural, one{записи} few {записей} many {записей} other{записи}}.', '{attribute} should contain at least {min, number} {min, plural, one{item} other{items}}.' => 'Количество объектов в {attribute} не должно быть меньше {min, number}{min, plural, one{} other{}}.', From f475ddcc039c1020c5db6a82ec11a871b04e5a68 Mon Sep 17 00:00:00 2001 From: shinybrad <83238715+shinybrad@users.noreply.github.com> Date: Sun, 1 Dec 2024 07:12:41 -0500 Subject: [PATCH 2/7] New translations app.php (Russian) [ci skip] --- src/translations/ru/app.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/translations/ru/app.php b/src/translations/ru/app.php index f6436710798..ebc2f047527 100644 --- a/src/translations/ru/app.php +++ b/src/translations/ru/app.php @@ -98,7 +98,7 @@ 'Allow custom options' => 'Разрешить пользовательские параметры', 'Allow line breaks' => 'Разрешить переносы строк', 'Allow public registration' => 'Разрешить публичную регистрацию', - 'Allow root-relative URLs' => 'Allow root-relative URLs', + 'Allow root-relative URLs' => 'Разрешить относительные URL-адреса', 'Allow self relations' => 'Разрешить ссылаться на себя', 'Allow subfolders' => 'Разрешить вложенные папки', 'Allow uploading directly to the field' => 'Разрешить загрузку непосредственно в поле', @@ -1696,7 +1696,7 @@ 'This field was updated in the Current revision.' => 'Данное поле было обновлено в текущей версии.', 'This field’s target subfolder path is invalid: {path}' => 'Путь к целевой подпапке в этом поле недействителен: {path}', 'This field’s values are used as search keywords.' => 'Значения данного поля используются в качестве ключевых слов поиска.', - 'This field’s {attributes} {totalAttributes, plural, =1{has} other{have}} been overridden.' => 'This field’s {attributes} {totalAttributes, plural, =1{has} other{have}} been overridden.', + 'This field’s {attributes} {totalAttributes, plural, =1{has} other{have}} been overridden.' => '{attributes} {totalAttributes, plural, =1{атрибут этого поля был переопределён} few{атрибута этого поля были переопределены} many {атрибутов этого поля были переопределены} other{атрибутов этого поля были переопределены}}.', 'This filesystem has been reserved for temporary asset uploads. Please choose a different one for your volume.' => 'Эта файловая система была зарезервирована для временной загрузки ресурсов. Выберите для вашего тома другую файловую систему.', 'This global set doesn’t have any fields assigned to it in its field layout.' => 'У этого глобального набора данных нет назначенных полей в его шаблоне полей.', 'This is a new {type}.' => 'Это новый тип {type}.', @@ -1872,7 +1872,7 @@ 'Validate related {type}' => 'Проверить связанный тип {type}', 'Validation errors for site: “{siteName}“' => 'Ошибки проверки для сайта: "{siteName}"', 'Validation errors found in {attribute} {type}; please fix them.' => 'В {attribute} {type} обнаружены ошибки проверки; исправьте их.', - 'Validation errors found in {count, plural, =1{one address} other{{count, spellout} addresses}} within the *{fieldName}* field; please fix them.' => 'Validation errors found in {count, plural, =1{one address} other{{count, spellout} addresses}} within the *{fieldName}* field; please fix them.', + 'Validation errors found in {count, plural, =1{one address} other{{count, spellout} addresses}} within the *{fieldName}* field; please fix them.' => 'Обнаружены ошибки валидации в {count, plural, =1{адресе} few{{count, spellout} адресах} many {{count, spellout} адресах} other{{count, spellout} адресах}} в поле *{fieldName}*; пожалуйста, исправьте их.', 'Validation errors found in {count, plural, =1{one nested entry} other{{count, spellout} nested entries}} within the *{fieldName}* field; please fix them.' => 'В {count, plural, one {} few {{count, spellout} вложенных записях} many {{count, spellout} nested entries}=1{одной вложенной записи} other{{count, spellout} вложенных записях}} в поле *{fieldName}* обнаружены ошибки проверки; исправьте их.', 'Value prefixed by “{prefix}”.' => 'Значение с префиксом “{prefix}”.', 'Value suffixed by “{suffix}”.' => 'Значение с суффиксом “{suffix}”.', @@ -2130,7 +2130,7 @@ '{attribute} should contain at most {max, number} {max, plural, one{item} other{items}}.' => 'Количество объектов в {attribute} не должно превышать {max, number}{max, plural, one{} other{}}.', '{attribute} should contain at most {max, number} {max, plural, one{selection} other{selections}}.' => 'Количество выбранных в {attribute} не должно превышать {max, number}{max, plural, one{} other{}}.', '{attribute} should contain {count, number} {count, plural, one{item} other{items}}.' => 'Количество объектов, которое должно находиться в {attribute}: {count, number}{count, plural, one{} other{}}.', - '{count, number} {count, plural, =1{layout} other{layouts}}' => '{count, number} {count, plural, =1{layout} other{layouts}}', + '{count, number} {count, plural, =1{layout} other{layouts}}' => '{count, number} {count, plural, =1{макет} few{макета} many {макетов} other{макетов}}', '{count, spellout} plugin {count, plural, =1{update} other{updates}}' => '{count, spellout} {count, plural, one {} few {обновления} many {обновлений}=1{обновление} other{обновления}} плагинов', '{count, spellout} {count, plural, =1{plugin} other{plugins}}' => '{count, spellout} {count, plural, one {} few {плагина} many {плагинов}=1{плагин} other{плагина}}', '{ctrl}C to copy.' => '{ctrl}C, чтобы скопировать.', @@ -2164,7 +2164,7 @@ '{num, number} {num, plural, =1{month} other{months}}' => '{num, number} {num, plural, =1{месяц} other{месяцы}} ', '{num, number} {num, plural, =1{notification} other{notifications}}' => '{num, number} {num, plural, one {уведомление} few {уведомления} many {уведомлений} other{уведомления}}', - '{num, number} {num, plural, =1{result} other{results}}' => '{num, number} {num, plural, =1{result} other{results}}', + '{num, number} {num, plural, =1{result} other{results}}' => '{num, number} {num, plural, =1{результат} few{результата} many {результатов} other{результатов}}', '{num, number} {num, plural, =1{second} other{seconds}}' => '{num, number} {num, plural, =1{секунда} other{секунды}}', '{num, number} {num, plural, =1{week} other{weeks}}' => '{num, number} {num, plural, =1{неделя} other{недели}}', '{num, number} {num, plural, =1{year} other{years}} of updates' => '{num, number} {num, plural, one {} few {года} many {лет}=1{год} other{года}} обновлений', From ccfe702b48ceb503841d5f09b57afd897acfcf9e Mon Sep 17 00:00:00 2001 From: Iwona Just Date: Mon, 2 Dec 2024 08:31:02 +0000 Subject: [PATCH 3/7] add missing data-error-key to the latLong field --- src/fieldlayoutelements/addresses/LatLongField.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/fieldlayoutelements/addresses/LatLongField.php b/src/fieldlayoutelements/addresses/LatLongField.php index 942c7b31d01..8547908200c 100644 --- a/src/fieldlayoutelements/addresses/LatLongField.php +++ b/src/fieldlayoutelements/addresses/LatLongField.php @@ -122,6 +122,9 @@ protected function inputHtml(ElementInterface $element = null, bool $static = fa 'name' => 'latitude', 'value' => $element->latitude, 'required' => $this->required, + 'data' => [ + 'error-key' => 'latitude', + ], ]) . Cp::textFieldHtml([ 'fieldClass' => 'width-50', @@ -130,6 +133,9 @@ protected function inputHtml(ElementInterface $element = null, bool $static = fa 'name' => 'longitude', 'value' => $element->longitude, 'required' => $this->required, + 'data' => [ + 'error-key' => 'longitude', + ], ]) . Html::endTag('div'); } From 0a04e9c3b3b07b1ee48b68f5e8a932cb36435c7d Mon Sep 17 00:00:00 2001 From: Ben Croker <57572400+bencroker@users.noreply.github.com> Date: Fri, 29 Nov 2024 13:06:23 -0600 Subject: [PATCH 4/7] Update ElementTrait.php Resolves #16247 --- src/base/ElementTrait.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/base/ElementTrait.php b/src/base/ElementTrait.php index c0caca6aff1..c998f6cc82f 100644 --- a/src/base/ElementTrait.php +++ b/src/base/ElementTrait.php @@ -196,7 +196,7 @@ trait ElementTrait public bool $resaving = false; /** - * @var ElementInterface|null The element that this element is being duplicated by. + * @var ElementInterface|null The element that this element is duplicating. */ public ?ElementInterface $duplicateOf = null; From 4ffe67fffca70c49fee409db3e4928aa97dc571e Mon Sep 17 00:00:00 2001 From: brandonkelly Date: Mon, 2 Dec 2024 10:07:32 -0800 Subject: [PATCH 5/7] Release note [ci skip] --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8d4e13ee04..3d1eeb5f360 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ - Fixed a bug where changes to nested elements weren’t getting saved to a draft of the parent, if the element editor was triggered via the “Edit” action menu item. ([#16251](https://github.com/craftcms/cms/issues/16251)) - Fixed a bug where all elements would get soft-deleted when deleting a section on PostgreSQL. ([#16230](https://github.com/craftcms/cms/issues/16230)) - Fixed a bug where entry cards could contain two entry type icons if the “Entry Type” attribute was included in the card view designer. ([#16234](https://github.com/craftcms/cms/issues/16234)) +- Fixed a bug where address error summaries weren’t linking to Latitude/Longitude fields properly. ([#16244](https://github.com/craftcms/cms/issues/16244)) - Fixed a styling issue. ## 5.5.3 - 2024-11-22 From 130fd77e0fce7213b9284cd1e9a62cd2505c5291 Mon Sep 17 00:00:00 2001 From: brandonkelly Date: Mon, 2 Dec 2024 10:54:24 -0800 Subject: [PATCH 6/7] Move element index variable prep into template hooks Fixes #16254 --- CHANGELOG.md | 1 + src/templates/_elements/sources.twig | 12 +--- src/templates/_elements/toolbar.twig | 11 +--- src/templates/_layouts/elementindex.twig | 19 +----- src/web/View.php | 73 ++++++++++++++++++++++++ 5 files changed, 80 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7824f1dff9f..3f2eacf96cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - Fixed a bug where renaming asset folders could move them to the webroot on Windows. ([#16215](https://github.com/craftcms/cms/issues/16215)) - Fixed a bug where Matrix fields’ content tables weren’t getting renamed properly when applying project config changes. ([#16227](https://github.com/craftcms/cms/issues/16227)) - Fixed a bug where utilities’ `isSelectable()` methods weren’t being respected. +- Fixed an exception that could be thrown when displaying entry indexes, if any `EVENT_INIT` or `EVENT_DEFINE_BEHAVIORS` entry event handlers were calling `getSection()` or `getType()` on the entry. ([#16254](https://github.com/craftcms/cms/issues/16254)) ## 4.13.3 - 2024-11-22 diff --git a/src/templates/_elements/sources.twig b/src/templates/_elements/sources.twig index 5ccf428dc30..64ee2abf912 100644 --- a/src/templates/_elements/sources.twig +++ b/src/templates/_elements/sources.twig @@ -1,16 +1,6 @@ {% apply spaceless %} -{% set keyPrefix = keyPrefix ?? '' %} -{% set isTopLevel = not keyPrefix %} -{% if isTopLevel %} - {% set elementInstance = craft.app.elements.createElement(elementType) %} - {% set baseSortOptions = elementInstance.sortOptions()|map((option, key) => { - label: option.label ?? option, - attr: option.attribute ?? option.orderBy ?? key, - defaultDir: option.defaultDir ?? 'asc', - })|values %} - {% set tableColumns = craft.app.elementSources.getAvailableTableAttributes(elementType) %} -{% endif %} +{% hook 'cp.elements.sources' %} {% macro sourceLink(key, source, isTopLevel, elementType, baseSortOptions, tableColumns) %} {{ tag('a', { diff --git a/src/templates/_elements/toolbar.twig b/src/templates/_elements/toolbar.twig index 67527415583..711f070de93 100644 --- a/src/templates/_elements/toolbar.twig +++ b/src/templates/_elements/toolbar.twig @@ -9,14 +9,7 @@ "Display as thumbnails", ]) %} -{% set elementInstance = craft.app.elements.createElement(elementType) %} -{% set context = context is defined ? context : 'index' %} -{% set showStatusMenu = (showStatusMenu is defined and showStatusMenu != 'auto' ? showStatusMenu : elementInstance.hasStatuses()) %} -{% set showSiteMenu = (craft.app.getIsMultiSite() ? (showSiteMenu ?? 'auto') : false) %} -{% if showSiteMenu is same as ('auto') %} - {% set showSiteMenu = elementInstance.isLocalized() %} -{% endif %} -{% set idPrefix = "elementtoolbar#{random()}-" %} +{% hook 'cp.elements.toolbar' %} {% if showStatusMenu or context == 'index' %}
@@ -26,7 +19,7 @@
  • {{ "All"|t('app') }}
  • {% if showStatusMenu %} - {% for status, info in elementInstance.statuses() %} + {% for status, info in elementStatuses %} {% set label = info.label ?? info %} {% set color = info.color ?? '' %}
  • {{ label }}
  • diff --git a/src/templates/_layouts/elementindex.twig b/src/templates/_layouts/elementindex.twig index c4e36ce672c..75aef9e47cb 100644 --- a/src/templates/_layouts/elementindex.twig +++ b/src/templates/_layouts/elementindex.twig @@ -1,19 +1,6 @@ {% extends '_layouts/cp.twig' %} -{% set elementInstance = craft.app.elements.createElement(elementType) %} -{% set title = title ?? elementInstance.pluralDisplayName() %} -{% set context = 'index' %} - -{% if not elementInstance %} - {% exit 404 %} -{% endif %} - -{% set sources = craft.app.elementSources.getSources(elementType, 'index', true) %} - -{% set showSiteMenu = (craft.app.getIsMultiSite() ? (showSiteMenu ?? 'auto') : false) %} -{% if showSiteMenu is same as ('auto') %} - {% set showSiteMenu = elementInstance.isLocalized() %} -{% endif %} +{% hook 'cp.layouts.elementindex' %} {% block contextMenu %} @@ -64,8 +51,8 @@ {% block initJs %} Craft.elementIndex = Craft.createElementIndex('{{ elementType|e("js") }}', $('#page-container'), { - elementTypeName: '{{ elementInstance.displayName()|e("js") }}', - elementTypePluralName: '{{ elementInstance.pluralDisplayName()|e("js") }}', + elementTypeName: '{{ elementDisplayName|e("js") }}', + elementTypePluralName: '{{ elementPluralDisplayName|e("js") }}', context: '{{ context }}', storageKey: 'elementindex.{{ elementType|e("js") }}', criteria: Craft.defaultIndexCriteria, diff --git a/src/web/View.php b/src/web/View.php index 610f46f0feb..b5829138d99 100644 --- a/src/web/View.php +++ b/src/web/View.php @@ -8,6 +8,7 @@ namespace craft\web; use Craft; +use craft\base\ElementInterface; use craft\events\AssetBundleEvent; use craft\events\CreateTwigEvent; use craft\events\RegisterTemplateRootsEvent; @@ -26,6 +27,7 @@ use craft\web\twig\GlobalsExtension; use craft\web\twig\SinglePreloaderExtension; use craft\web\twig\TemplateLoader; +use Illuminate\Support\Collection; use LogicException; use Throwable; use Twig\Error\LoaderError as TwigLoaderError; @@ -361,6 +363,9 @@ public function init(): void } // Register the control panel hooks + $this->hook('cp.layouts.elementindex', [$this, '_prepareElementIndexVariables']); + $this->hook('cp.elements.toolbar', [$this, '_prepareElementToolbarVariables']); + $this->hook('cp.elements.sources', [$this, '_prepareElementSourcesVariables']); $this->hook('cp.elements.element', [$this, '_getCpElementHtml']); } @@ -2383,6 +2388,74 @@ private function _setJsProperty(string $property, array $names): void $this->registerJs($js, self::POS_HEAD); } + /** @phpstan-ignore-next-line */ + private function _prepareElementIndexVariables(array &$context): ?string + { + /** @var class-string $elementType */ + $elementType = $context['elementType']; + + $context['title'] ??= $elementType::pluralDisplayName(); + $context['context'] = 'index'; + $context['sources'] = Craft::$app->getElementSources()->getSources($elementType, withDisabled: true); + + $context['showSiteMenu'] = Craft::$app->getIsMultiSite() ? ($context['showSiteMenu'] ?? 'auto') : false; + if ($context['showSiteMenu'] === 'auto') { + $context['showSiteMenu'] = $elementType::isLocalized(); + } + + $context['elementDisplayName'] = $elementType::displayName(); + $context['elementPluralDisplayName'] = $elementType::pluralDisplayName(); + + return null; + } + + /** @phpstan-ignore-next-line */ + private function _prepareElementToolbarVariables(array &$context): ?string + { + /** @var class-string $elementType */ + $elementType = $context['elementType']; + + $context['context'] ??= 'index'; + $context['showStatusMenu'] ??= 'auto'; + if ($context['showStatusMenu'] === 'auto') { + $context['showStatusMenu'] = $elementType::hasStatuses(); + } + $context['showSiteMenu'] = Craft::$app->getIsMultiSite() ? ($context['showSiteMenu'] ?? 'auto') : false; + if ($context['showSiteMenu'] === 'auto') { + $context['showSiteMenu'] = $elementType::isLocalized(); + } + $context['idPrefix'] = sprintf('elementtoolbar%s-', mt_rand()); + + if ($context['showStatusMenu']) { + $context['elementStatuses'] = $elementType::statuses(); + } + + return null; + } + + /** @phpstan-ignore-next-line */ + private function _prepareElementSourcesVariables(array &$context): ?string + { + $context['keyPrefix'] ??= ''; + $context['isTopLevel'] = $context['keyPrefix'] === ''; + + if ($context['isTopLevel']) { + /** @var class-string $elementType */ + $elementType = $context['elementType']; + $context['baseSortOptions'] = Collection::make($elementType::sortOptions()) + ->map(fn($option, $key) => [ + 'label' => $option['label'] ?? $option, + 'attr' => $option['attribute'] ?? $option['orderBy'] ?? $key, + 'defaultDir' => $option['defaultDir'] ?? 'asc', + ]) + ->values() + ->all(); + $context['tableColumns'] = Craft::$app->getElementSources()->getAvailableTableAttributes($elementType); + } + + return null; + } + /** * Returns the HTML for an element in the control panel. * From eff667160a318a8301304481ff2b36b0edcca505 Mon Sep 17 00:00:00 2001 From: brandonkelly Date: Mon, 2 Dec 2024 11:16:56 -0800 Subject: [PATCH 7/7] No need to instantiate the element here Additional fix for #16254 --- src/models/FieldLayout.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/models/FieldLayout.php b/src/models/FieldLayout.php index 0fb27d7c42d..af0bc2d65b9 100644 --- a/src/models/FieldLayout.php +++ b/src/models/FieldLayout.php @@ -794,12 +794,10 @@ public function getCardBodyFields(?ElementInterface $element): array public function getCardBodyAttributes(): array { $cardViewValues = $this->getCardView(); - /** @var ElementInterface $elementType */ - $elementType = new ($this->type); // filter only the selected attributes $attributes = array_filter( - $elementType::cardAttributes(), + $this->type::cardAttributes(), fn($cardAttribute, $key) => in_array($key, $cardViewValues), ARRAY_FILTER_USE_BOTH );