diff --git a/src/FormBuilder.php b/src/FormBuilder.php index c701de9..e4ce357 100644 --- a/src/FormBuilder.php +++ b/src/FormBuilder.php @@ -1012,6 +1012,50 @@ class FormBuilder return $this->toHtmlString('html->attributes($options) . '>' . $value . ''); } + /** + * Create a datalist box field. + * + * @param string $id + * @param array $list + * + * @return \Illuminate\Support\HtmlString + */ + public function datalist($id, $list = []) + { + $this->type = 'datalist'; + + $attributes['id'] = $id; + + $html = []; + + if ($this->isAssociativeArray($list)) { + foreach ($list as $value => $display) { + $html[] = $this->option($display, $value, null, []); + } + } else { + foreach ($list as $value) { + $html[] = $this->option($value, $value, null, []); + } + } + + $attributes = $this->html->attributes($attributes); + + $list = implode('', $html); + + return $this->toHtmlString("{$list}"); + } + + /** + * Determine if an array is associative. + * + * @param array $array + * @return bool + */ + protected function isAssociativeArray($array) + { + return (array_values($array) !== $array); + } + /** * Parse the form action method. * diff --git a/tests/FormBuilderTest.php b/tests/FormBuilderTest.php index dc98c81..90f2165 100644 --- a/tests/FormBuilderTest.php +++ b/tests/FormBuilderTest.php @@ -714,6 +714,24 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase $this->assertEquals('', $form3); } + public function testDatalist() + { + // Associative array with string keys. + $genders = ['M' => 'Male', 'F' => 'Female']; + $datalist = $this->formBuilder->datalist('genders', $genders); + $this->assertEquals('', $datalist); + + // Associative array with numeric Keys + $genders = [5 => 'Male', 6 => 'Female']; + $datalist = $this->formBuilder->datalist('genders', $genders); + $this->assertEquals('', $datalist); + + // Not associative array. + $genders = ['Male', 'Female']; + $datalist = $this->formBuilder->datalist('genders', $genders); + $this->assertEquals('', $datalist); + } + public function testBooleanAttributes() { $input = $this->formBuilder->text('test', null, ['disabled']);