Skip to content

Commit

Permalink
Improved handling of composite keys in unique constraint violation
Browse files Browse the repository at this point in the history
  • Loading branch information
juniwalk authored May 17, 2023
1 parent e6a65c0 commit b77cd7a
Showing 1 changed file with 26 additions and 25 deletions.
51 changes: 26 additions & 25 deletions src/AbstractForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Doctrine\DBAL\Exception\UniqueConstraintViolationException as UniqueException;
use JuniWalk\Form\Enums\Layout;
use JuniWalk\Form\Tools\SearchPayload;
use JuniWalk\Utils\Arrays;
use JuniWalk\Utils\Format;
use JuniWalk\Utils\Strings;
use Nette\Application\AbortException;
Expand Down Expand Up @@ -280,6 +281,21 @@ public function render(): void
}


/**
* @internal
*/
protected function findSubmitButton(): ?SubmitterControl
{
$buttons = $this->getComponents(true, SubmitterControl::class);

if (!$buttons = iterator_to_array($buttons)) {
return null;
}

return $buttons['submit'] ?? current($buttons);
}


protected function createComponentForm(): Form
{
$form = new $this->formClass;
Expand Down Expand Up @@ -319,24 +335,6 @@ protected function handleSuccess(Form $form, ArrayHash $data): void
}


/**
* @internal
*/
protected function findSubmitButton(): ?SubmitterControl
{
$buttons = $this->getComponents(true, SubmitterControl::class);

if (!$buttons = iterator_to_array($buttons)) {
return null;
}

return $buttons['submit'] ?? current($buttons);
}


/**
* @internal
*/
protected function handleUniqueConstraintViolation(UniqueException $e, callable $callback = null, array $fieldMap = []): void
{
$callback = $callback ?? fn() => null;
Expand All @@ -355,21 +353,24 @@ protected function handleUniqueConstraintViolation(UniqueException $e, callable
Strings::split($fields['value'], '/,\s?/')
);

foreach ($fields as $field => $value) {
$field = $fieldMap[$field] ?? Format::camelCase($field);
$message = $callback($field) ?? $defaultMessage;
$fields = Arrays::walk($fields, fn($value, $field) =>
yield $fieldMap[$field] ?? Format::camelCase($field) => $value
);

$fieldKey = implode('-', array_keys($fields));
$message = $callback($fieldKey) ?? $defaultMessage;
$message = new Message($message, $fields);

foreach ($fields as $field => $value) {
if (!$form->getComponent($field, false)) {
continue;
}

$form[$field]->addError(new Message($message, [
'value' => $value,
]));
$form[$field]->addError($message);
}

if (!$form->hasErrors()) {
$form->addError($defaultMessage);
$form->addError($message);
}
}
}

0 comments on commit b77cd7a

Please sign in to comment.