Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Taxonomy Term Removal #16538

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -311,18 +311,18 @@ public async Task<IActionResult> Delete(string taxonomyContentItemId, string tax
}

// Look for the target taxonomy item in the hierarchy.
var taxonomyItem = FindTaxonomyItem((JsonObject)taxonomy.As<TaxonomyPart>().Content, taxonomyItemId);
var content = (JsonObject)taxonomy.As<TaxonomyPart>().Content;

// Couldn't find targeted taxonomy item.
if (taxonomyItem == null)
RemoveTaxonomyItem(content, taxonomyItemId);

var updatedPart = content.ToObject<TaxonomyPart>();

if (updatedPart == null)
{
return NotFound();
}

taxonomy.Alter<TaxonomyPart>(part =>
{
part.Terms = part.Terms.Where(x => x.ContentItemId != taxonomyItemId).ToList();
});
taxonomy.Apply(updatedPart);

await _session.SaveAsync(taxonomy);

Expand Down Expand Up @@ -357,5 +357,36 @@ private static JsonObject FindTaxonomyItem(JsonObject contentItem, string taxono

return null;
}

private static bool RemoveTaxonomyItem(JsonObject contentItem, string taxonomyItemToRemove)
{
if (contentItem == null)
{
return false;
}

if (contentItem["ContentItemId"]?.Value<string>() == taxonomyItemToRemove)
{
return true;
}

if (!contentItem.TryGetPropertyValue("Terms", out var terms) || terms is not JsonArray taxonomyItems)
{
return false;
}

for (var i = taxonomyItems.Count - 1; i >= 0; i--)
{
var taxonomyItem = taxonomyItems[i] as JsonObject;
if (RemoveTaxonomyItem(taxonomyItem, taxonomyItemToRemove))
{
taxonomyItems.RemoveAt(i);

return false;
}
}

return false;
}
}
}