From fda9d3dad85ecea609ef9c6323d6923536cf5643 Mon Sep 17 00:00:00 2001 From: ThunderbirdsX3 Date: Wed, 30 May 2018 23:09:07 +0700 Subject: [PATCH] Can set class attribute in array. (#521) In case of you want to add class by condition. ``` Form::text('name', null, ['class' => [ 'form-control-, $error ? 'is-invalid' : '', ]]); ``` --- src/HtmlBuilder.php | 4 ++++ tests/FormBuilderTest.php | 12 ++++++++++++ tests/HtmlBuilderTest.php | 14 ++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/src/HtmlBuilder.php b/src/HtmlBuilder.php index 17da19f5..743b32a0 100755 --- a/src/HtmlBuilder.php +++ b/src/HtmlBuilder.php @@ -455,6 +455,10 @@ protected function attributeElement($key, $value) return $value ? $key : ''; } + if (is_array($value) && $key === 'class') { + return 'class="' . implode(' ', $value) . '"'; + } + if (! is_null($value)) { return $key . '="' . e($value, false) . '"'; } diff --git a/tests/FormBuilderTest.php b/tests/FormBuilderTest.php index 6936a5f2..35d43c0e 100644 --- a/tests/FormBuilderTest.php +++ b/tests/FormBuilderTest.php @@ -792,6 +792,18 @@ public function testBooleanAttributes() $this->assertEquals('', $input); } + public function testArrayClassAttributes() + { + $input = $this->formBuilder->text('test', null, ['class' => ['class-a', 'class-b']]); + $this->assertEquals('', $input); + + $input = $this->formBuilder->text('test', null, ['class' => [ + 'class-a', + false ? 'class-b' : 'class-c' + ]]); + $this->assertEquals('', $input); + } + protected function setModel(array $data, $object = true) { if ($object) { diff --git a/tests/HtmlBuilderTest.php b/tests/HtmlBuilderTest.php index a5a9ee27..f79320af 100644 --- a/tests/HtmlBuilderTest.php +++ b/tests/HtmlBuilderTest.php @@ -151,4 +151,18 @@ public function testBooleanAttributes() $this->assertEquals('', trim($result2)); } + + public function testArrayClassAttributes() + { + $result = $this->htmlBuilder->attributes(['class' => ['class-a', 'class-b']]); + + $this->assertEquals('class="class-a class-b"', trim($result)); + + $result = $this->htmlBuilder->attributes(['class' => [ + 'class-a', + false ? 'class-b' : 'class-c' + ]]); + + $this->assertEquals('class="class-a class-c"', trim($result)); + } }