Skip to content

Commit

Permalink
[5.x] Add validation replacements to replicator and grid field types (#…
Browse files Browse the repository at this point in the history
…10255)

Co-authored-by: Florian Brinkmann <[email protected]>
Co-authored-by: Jason Varga <[email protected]>
  • Loading branch information
3 people authored Dec 5, 2024
1 parent 278ca3c commit 313b2a6
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
32 changes: 32 additions & 0 deletions src/Fieldtypes/AddsEntryValidationReplacements.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Statamic\Fieldtypes;

use Statamic\Entries\Entry;
use Statamic\Fields\Field;
use Statamic\Fields\Validator;

/**
* TODO
* This allows Grid/Replicator/Bard fields to add validation replacements.
* It adds the same replacements that get added in EntriesController@update.
* Ideally those would get passed down into the field automatically somehow,
* so this can be considered a workaround until that happens.
*/
trait AddsEntryValidationReplacements
{
protected function addEntryValidationReplacements(Field $field, Validator $rules): Validator
{
$fieldParent = $field->parent();

if (! $fieldParent instanceof Entry) {
return $rules;
}

return $rules->withReplacements([
'id' => $fieldParent->id(),
'collection' => $fieldParent->collection()->handle(),
'site' => $fieldParent->locale(),
]);
}
}
7 changes: 6 additions & 1 deletion src/Fieldtypes/Grid.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

class Grid extends Fieldtype
{
use AddsEntryValidationReplacements;

protected $categories = ['structured'];
protected $defaultable = false;

Expand Down Expand Up @@ -158,7 +160,10 @@ protected function rowRules($data, $index)
->validator()
->withContext([
'prefix' => $this->field->validationContext('prefix').$this->rowRuleFieldPrefix($index).'.',
])
]);

$rules = $this
->addEntryValidationReplacements($this->field, $rules)
->rules();

return collect($rules)->mapWithKeys(function ($rules, $handle) use ($index) {
Expand Down
7 changes: 6 additions & 1 deletion src/Fieldtypes/Replicator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

class Replicator extends Fieldtype
{
use AddsEntryValidationReplacements;

protected $categories = ['structured'];
protected $keywords = ['builder', 'page builder', 'content'];
protected $rules = ['array'];
Expand Down Expand Up @@ -150,7 +152,10 @@ protected function setRules($handle, $data, $index)
->validator()
->withContext([
'prefix' => $this->field->validationContext('prefix').$this->setRuleFieldPrefix($index).'.',
])
]);

$rules = $this
->addEntryValidationReplacements($this->field, $rules)
->rules();

return collect($rules)->mapWithKeys(function ($rules, $handle) use ($index) {
Expand Down

0 comments on commit 313b2a6

Please sign in to comment.