diff --git a/resources/lang/en/fieldtypes.php b/resources/lang/en/fieldtypes.php index 8cc5d230cf..3159ab436b 100644 --- a/resources/lang/en/fieldtypes.php +++ b/resources/lang/en/fieldtypes.php @@ -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', diff --git a/src/Fieldtypes/Entries.php b/src/Fieldtypes/Entries.php index 21b5371ade..cfb619fa7b 100644 --- a/src/Fieldtypes/Entries.php +++ b/src/Fieldtypes/Entries.php @@ -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'), + ], + ], ], ], ]; @@ -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() @@ -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(); + } }