From 52d1388e4e7d7165695af889f8dcc861086ad012 Mon Sep 17 00:00:00 2001 From: Luke Towers Date: Sun, 26 Aug 2018 13:39:49 -0600 Subject: [PATCH] Automatically use field labels as custom attribute names for a nicer validation message Fixes #2489 --- modules/backend/behaviors/FormController.php | 25 ++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/modules/backend/behaviors/FormController.php b/modules/backend/behaviors/FormController.php index 60f27aa09..71e9567f6 100644 --- a/modules/backend/behaviors/FormController.php +++ b/modules/backend/behaviors/FormController.php @@ -9,6 +9,7 @@ use Input; use Redirect; use Backend; use Backend\Classes\ControllerBehavior; +use October\Rain\Html\Helper as HtmlHelper; use October\Rain\Router\Helper as RouterHelper; use ApplicationException; use Exception; @@ -232,6 +233,7 @@ class FormController extends ControllerBehavior $this->initForm($model); + $this->controller->formSetValidationNames($model); $this->controller->formBeforeSave($model); $this->controller->formBeforeCreate($model); @@ -299,6 +301,7 @@ class FormController extends ControllerBehavior $model = $this->controller->formFindModelObject($recordId); $this->initForm($model); + $this->controller->formSetValidationNames($model); $this->controller->formBeforeSave($model); $this->controller->formBeforeUpdate($model); @@ -678,6 +681,28 @@ class FormController extends ControllerBehavior // Overrides // + /** + * Called before the creation or updating form is saved to override the field names for validation using their labels + */ + public function formSetValidationNames($model) + { + $attributeNames = []; + $form = $this->formGetWidget(); + foreach ($form->getFields() as $field) { + $fieldName = implode('.', HtmlHelper::nameToArray($field->fieldName)); + $attributeNames[$fieldName] = $field->label; + } + if (!property_exists($model, 'attributeNames')) { + $model->addDynamicProperty('attributeNames', $attributeNames); + // Clean up after validation to prevent attributeNames from being handled as a model attribute to be saved in the DB + $model->bindEvent('model.afterValidate', function () use ($model) { + unset($model->attributes['attributeNames']); + }); + } else { + $model->attributeNames = array_merge($attributeNames, (array) $model->attributeNames); + } + } + /** * Called before the creation or updating form is saved. * @param Model