Added flag to display a single model error for MediaLibraryPickerField (#8700)

* Added flag to display model error by LocalizationExtensionHandler if media have been removed from the field only. This ensures that no duplicate model error has displayed.

* Restored formatting for else branches

---------

Co-authored-by: Matteo Piovanelli <MatteoPiovanelli-Laser@users.noreply.github.com>
This commit is contained in:
Andrea Piovanelli
2023-06-30 08:49:20 +02:00
committed by GitHub
co-authored by Matteo Piovanelli
parent 0485e44378
commit 0b001c76c2
@@ -45,6 +45,12 @@ namespace Orchard.MediaLibrary.Handlers {
//try to replace items in the field with their translation
var itemsInField = _contentManager.GetMany<ContentItem>(field.Ids, VersionOptions.Latest, QueryHints.Empty);
var mediaIds = new List<int>();
// Flag to check if media have been removed from the field.
// This happens when the field is set to remove items without localization and one or more media items cannot be localized.
// This flag is used to display a model error when the field is required and every media item has been removed from it.
var mediaRemoved = false;
foreach (var item in itemsInField) {
// negatives id whoud be localized
var mediaItem = _contentManager.Get(item.Id, VersionOptions.Latest);
@@ -98,6 +104,7 @@ namespace Orchard.MediaLibrary.Handlers {
"{0}: the media item {1} has been removed from the field because its culture differs from content's culture",
field.DisplayName,
mediaItem.As<MediaPart>().FileName));
mediaRemoved = true;
}
}
}
@@ -112,13 +119,14 @@ namespace Orchard.MediaLibrary.Handlers {
"{0}: the media item {1} has been removed from the field because culture neutral",
field.DisplayName,
mediaItem.As<MediaPart>().FileName));
mediaRemoved = true;
}
}
}
field.Ids = mediaIds.Distinct().ToArray();
if (field.Ids.Length == 0 && fieldSettings.Required) {
if (field.Ids.Length == 0 && fieldSettings.Required && mediaRemoved) {
context.Updater.AddModelError("Id", T("The {0} field is required.", field.DisplayName));
}
}