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
39 changes: 28 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,44 @@ public function getSaveValue($value)
*/
protected function hydrateRelationSaveValue($names): ?array
{
if (!$names) {
return $names;
}

if (!is_array($names)) {
$names = [$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
6 changes: 5 additions & 1 deletion modules/backend/widgets/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -1227,7 +1227,11 @@ public function getSaveData(): array
// Exclude fields that didn't provide any value
$fieldValue = $this->dataArrayGet($result, $parts, FormField::NO_SAVE_DATA);
if ($fieldValue === FormField::NO_SAVE_DATA) {
continue;
if ($widget->getConfig('type') === 'taglist') {
$fieldValue = in_array($widget->getConfig('mode'), ['array','relation']) ? [] : '';
} else {
continue;
}
mjauvin marked this conversation as resolved.
Show resolved Hide resolved
}

// Exclude fields where the widget returns NO_SAVE_DATA
Expand Down
Loading