Skip to content

Commit

Permalink
Add option to link entries by slug
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanmitchell committed Oct 25, 2023
1 parent c24b698 commit 0c1bb56
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions resources/lang/en/fieldtypes.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
'date.title' => 'Date',
'entries.config.create' => 'Allow creation of new entries.',
'entries.config.collections' => 'Choose which collections the user can select from.',
'entries.config.link_by' => 'Choose what field to use to link items. If you choose slug make sure slugs are unique in your linked collection(s).',
'entries.config.query_scopes' => 'Choose which query scopes should be applied when retrieving selectable entries.',
'entries.title' => 'Entries',
'float.title' => 'Float',
Expand Down
49 changes: 49 additions & 0 deletions src/Fieldtypes/Entries.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,16 @@ protected function configFieldItems(): array
'instructions' => __('statamic::fieldtypes.entries.config.query_scopes'),
'type' => 'taggable',
],
'link_by' => [
'display' => __('Link By'),
'instructions' => __('statamic::fieldtypes.entries.config.link_by'),
'type' => 'select',
'default' => 'id',
'options' => [
'id' => __('ID'),
'slug' => __('Slug'),
],
],
],
],
];
Expand Down Expand Up @@ -278,6 +288,10 @@ public function augment($values)
$site = $parent->locale();
}

if ($this->config('link_by') == 'slug') {
$values = $this->replaceSlugsWithIds($values);
}

$ids = (new OrderedQueryBuilder(Entry::query(), $ids = Arr::wrap($values)))
->whereIn('id', $ids)
->get()
Expand Down Expand Up @@ -358,4 +372,39 @@ public function filter()
{
return new EntriesFilter($this);
}

public function process($data)
{
$data = parent::process($data);

if ($this->config('link_by') == 'slug') {
$data = collect($data)->map(function ($item) {
if ($entry = Entry::find($item)) {
return $entry->slug();
}
})->filter()->all();
}

return $data;
}

public function preProcess($data)
{
$data = parent::preProcess($data);

if ($this->config('link_by') == 'slug') {
$data = $this->replaceSlugsWithIds($data);
}

return $data;
}

private function replaceSlugsWithIds($data)
{
return collect($data)->map(function ($item) {
if ($entry = Entry::query()->whereIn('collection', $this->getConfiguredCollections())->where('slug', $item)->first()) {
return $entry->id();
}
})->filter()->all();
}
}

0 comments on commit 0c1bb56

Please sign in to comment.