Skip to content

Commit

Permalink
Fix TagList formwidget (#1267)
Browse files Browse the repository at this point in the history
The TagList formwidget was not working properly in relation mode if the relation was not using a pivot table (e.g. morphMany/hasMany)

All modes did not update the model field or relation when all tags had been cleared.

Fixes #1223
  • Loading branch information
mjauvin authored Dec 19, 2024
1 parent d2d55ef commit 20a73ff
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 11 deletions.
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

0 comments on commit 20a73ff

Please sign in to comment.