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 TagList formwidget #1267

Merged
merged 9 commits into from
Dec 19, 2024
41 changes: 30 additions & 11 deletions modules/backend/formwidgets/TagList.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use Backend\Classes\FormWidgetBase;
use Illuminate\Database\Eloquent\Relations\Relation as RelationBase;
use Winter\Storm\Database\Relations\BelongsToMany;
use Winter\Storm\Database\Relations\MorphToMany;

/**
* Tag List Form Widget
Expand Down Expand Up @@ -125,29 +127,46 @@ public function getSaveValue($value)
*/
protected function hydrateRelationSaveValue($names): ?array
{
if (!$names) {
return $names;
}

if (!is_array($names)) {
$names = [$names];
}

$names = array_filter($names);

$relation = $this->getRelationObject();
$relationModel = $this->getRelationModel();
$existingTags = $relationModel
->whereIn($this->nameFrom, $names)
->lists($this->nameFrom, $relationModel->getKeyName())
;

$keyName = $relationModel->getKeyName();
$pivot = in_array(get_class($relation), [BelongsToMany::class, MorphToMany::class]);

if ($pivot) {
$existingTags = $relationModel->whereIn($this->nameFrom, $names)->lists($this->nameFrom, $keyName);
} else {
$existingTags = $relation->lists($this->nameFrom, $keyName);
}

$newTags = $this->customTags ? array_diff($names, $existingTags) : [];
$deletedTags = $this->customTags ? array_diff($existingTags, $names) : [];

foreach ($newTags as $newTag) {
$newModel = new $relationModel;
$newModel->{$this->nameFrom} = $newTag;
$newModel->save();
if ($pivot) {
$newModel = new $relationModel;
$newModel->{$this->nameFrom} = $newTag;
$newModel->save();
} else {
$newModel = $relation->create([$this->nameFrom => $newTag]);
}
$existingTags[$newModel->getKey()] = $newTag;
}

if (!$pivot && $deletedTags) {
$deletedKeys = array_keys($deletedTags);
$relation->whereIn($keyName, $deletedKeys)->delete();
foreach ($deletedTags as $id) {
unset($existingTags[$id]);
}
}

return array_keys($existingTags);
}

Expand Down
1 change: 1 addition & 0 deletions modules/backend/formwidgets/taglist/partials/_taglist.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
value="<?= $field->value ?>">
<?php endif ?>
<?php else: ?>
<input type="hidden" name="<?= $field->getName() ?>[]">
<select
id="<?= $field->getId() ?>"
name="<?= $field->getName() ?>[]"
Expand Down
Loading