Skip to content

Commit 52023ef

Browse files
authored
Merge pull request #72 from IsraelOrtuno/master
Add validation support for arrays of inputs
2 parents e9560fc + 130e24a commit 52023ef

2 files changed

Lines changed: 28 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: 7 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,12 @@ 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+
$name = str_replace(['[', ']'], ['.', ''], $name);
644+
644645
return $errors->get($name, []);
645646
}
646647
}
@@ -738,7 +739,7 @@ protected function doBuild($type, $name, $value = null, array $attributes = arra
738739
$label = $this->getLabel($name, $attributes);
739740
$htmlName = $this->getHtmlName($name);
740741
$id = $this->getHtmlId($name, $attributes);
741-
$errors = $this->getControlErrors($id);
742+
$errors = $this->getControlErrors($name);
742743
$hasErrors = !empty($errors);
743744
$customTemplate = $this->getCustomTemplate($attributes);
744745

0 commit comments

Comments
 (0)