Skip to content

Commit 96c8682

Browse files
IsraelOrtunosileence
authored andcommitted
Add support for arrays of inputs
1 parent 44dc95e commit 96c8682

2 files changed

Lines changed: 30 additions & 6 deletions

File tree

spec/FieldBuilderSpec.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,27 @@ function it_generates_a_text_field_with_errors($form, $theme, $lang, Session $se
205205
$this->text('name', 'value');
206206
}
207207

208+
function it_generates_an_array_of_inputs_with_errors($form, $theme, $lang, Session $session)
209+
{
210+
// Having
211+
$session->get('errors')->willReturn(new MessageBag([
212+
'group.name' => ['This is wrong']
213+
]));
214+
215+
$this->setSessionStore($session);
216+
217+
// Expect
218+
$form->text("group[name]", "value", ["class" => "error", "id" => "group_name"])->shouldBeCalled();
219+
$theme->render(
220+
null,
221+
Argument::withEntry('errors', ['This is wrong']),
222+
"fields.default"
223+
)->shouldBeCalled();
224+
225+
// When
226+
$this->text('group[name]', 'value');
227+
}
228+
208229
function it_generates_a_text_field_with_extra_data($theme)
209230
{
210231
// Expect

src/FieldBuilder.php

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -533,11 +533,7 @@ protected function getHtmlId($value, $attributes)
533533
return $attributes['id'];
534534
}
535535

536-
if (strpos($value, '.')) {
537-
return str_replace('.', '_', $value);
538-
}
539-
540-
return $value;
536+
return str_replace(['.', '[', ']'], ['_', '_', ''], $value);
541537
}
542538

543539
/**
@@ -640,7 +636,14 @@ protected function getClasses($type, array $attributes = [], $errors = null)
640636
protected function getControlErrors($name)
641637
{
642638
if ($this->session) {
639+
643640
if ($errors = $this->session->get('errors')) {
641+
642+
// Replaces to get errors on nested fields
643+
if (strpos($name, "[")) {
644+
$name = str_replace(['[', ']'], ['.', ''], $name);
645+
}
646+
644647
return $errors->get($name, []);
645648
}
646649
}
@@ -738,7 +741,7 @@ protected function doBuild($type, $name, $value = null, array $attributes = arra
738741
$label = $this->getLabel($name, $attributes);
739742
$htmlName = $this->getHtmlName($name);
740743
$id = $this->getHtmlId($name, $attributes);
741-
$errors = $this->getControlErrors($id);
744+
$errors = $this->getControlErrors($name);
742745
$hasErrors = !empty($errors);
743746
$customTemplate = $this->getCustomTemplate($attributes);
744747

0 commit comments

Comments
 (0)