diff --git a/src/Screen/Field.php b/src/Screen/Field.php index 5d971934c..091bec44f 100644 --- a/src/Screen/Field.php +++ b/src/Screen/Field.php @@ -31,6 +31,7 @@ * @method self style($value = true) * @method self tabindex($value = true) * @method self autocomplete($value = true) + * @method self addClass($value = true) */ class Field implements Fieldable, Htmlable { @@ -542,4 +543,22 @@ public function toHtml() { return $this->render()->toHtml(); } + + /** + * Add a class to the field including the existing classes. + * + * @param string|array $classes + * + * @return static + */ + public function addClass(string|array $classes): self + { + $currentClasses = array_filter(explode(' ', $this->get('class', ''))); + $newClasses = is_array($classes) ? $classes : explode(' ', $classes); + + $mergedClasses = array_unique(array_merge($currentClasses, $newClasses)); + $this->set('class', implode(' ', array_filter($mergedClasses))); + + return $this; + } } diff --git a/tests/Unit/FieldTest.php b/tests/Unit/FieldTest.php index 478e2b996..06a1dbdd2 100644 --- a/tests/Unit/FieldTest.php +++ b/tests/Unit/FieldTest.php @@ -217,4 +217,44 @@ public function testNumericOldName(): void $this->assertSame('3.141', Input::make('numeric')->getOldValue()); } + + public function testAddsSingleClassToEmptyClassAttribute(): void + { + $field = Field::make('test'); + $field->addClass('new-class'); + + $this->assertEquals('new-class', $field->get('class')); + } + + public function testAddsMultipleClassesToEmptyClassAttribute(): void + { + $field = Field::make('test'); + $field->addClass('class1 class2'); + + $this->assertEquals('class1 class2', $field->get('class')); + } + + public function testAddsArrayOfClassesToEmptyClassAttribute(): void + { + $field = Field::make('test'); + $field->addClass(['class1', 'class2']); + + $this->assertEquals('class1 class2', $field->get('class')); + } + + public function testAddsNewClassToExistingClasses(): void + { + $field = Field::make('test')->set('class', 'existing-class'); + $field->addClass('new-class'); + + $this->assertEquals('existing-class new-class', $field->get('class')); + } + + public function testDoesNotDuplicateClasses(): void + { + $field = Field::make('test')->set('class', 'existing-class'); + $field->addClass('existing-class new-class'); + + $this->assertEquals('existing-class new-class', $field->get('class')); + } }