| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | namespace Atk4\Ui; |
| 6: | |
| 7: | use Atk4\Core\Factory; |
| 8: | use Atk4\Data\Field; |
| 9: | use Atk4\Data\Model; |
| 10: | use Atk4\Data\Model\EntityFieldPair; |
| 11: | use Atk4\Data\Reference\ContainsMany; |
| 12: | use Atk4\Data\ValidationException; |
| 13: | use Atk4\Ui\Form\Control; |
| 14: | use Atk4\Ui\Js\Jquery; |
| 15: | use Atk4\Ui\Js\JsBlock; |
| 16: | use Atk4\Ui\Js\JsChain; |
| 17: | use Atk4\Ui\Js\JsConditionalForm; |
| 18: | use Atk4\Ui\Js\JsExpression; |
| 19: | use Atk4\Ui\Js\JsExpressionable; |
| 20: | |
| 21: | class Form extends View |
| 22: | { |
| 23: | use \Atk4\Core\HookTrait; |
| 24: | |
| 25: | |
| 26: | public const HOOK_SUBMIT = self::class . '@submit'; |
| 27: | |
| 28: | public const HOOK_DISPLAY_ERROR = self::class . '@displayError'; |
| 29: | |
| 30: | public const HOOK_DISPLAY_SUCCESS = self::class . '@displaySuccess'; |
| 31: | |
| 32: | public const HOOK_LOAD_POST = self::class . '@loadPost'; |
| 33: | |
| 34: | public $ui = 'form'; |
| 35: | public $defaultTemplate = 'form.html'; |
| 36: | |
| 37: | |
| 38: | public $cb; |
| 39: | |
| 40: | |
| 41: | public $canLeave = true; |
| 42: | |
| 43: | |
| 44: | |
| 45: | |
| 46: | |
| 47: | |
| 48: | |
| 49: | public $formElement; |
| 50: | |
| 51: | |
| 52: | public $layout; |
| 53: | |
| 54: | |
| 55: | public $controls = []; |
| 56: | |
| 57: | |
| 58: | |
| 59: | |
| 60: | |
| 61: | |
| 62: | |
| 63: | public $buttonSave = [Button::class, 'Save', 'class.primary' => true]; |
| 64: | |
| 65: | |
| 66: | |
| 67: | |
| 68: | |
| 69: | |
| 70: | |
| 71: | |
| 72: | |
| 73: | |
| 74: | public $successTemplate = 'form-success.html'; |
| 75: | |
| 76: | |
| 77: | |
| 78: | |
| 79: | |
| 80: | |
| 81: | |
| 82: | |
| 83: | |
| 84: | |
| 85: | |
| 86: | |
| 87: | |
| 88: | |
| 89: | |
| 90: | |
| 91: | |
| 92: | |
| 93: | |
| 94: | |
| 95: | |
| 96: | |
| 97: | public array $controlDisplayRules = []; |
| 98: | |
| 99: | |
| 100: | |
| 101: | |
| 102: | |
| 103: | |
| 104: | |
| 105: | |
| 106: | public $controlDisplaySelector = '.field'; |
| 107: | |
| 108: | |
| 109: | public $apiConfig = []; |
| 110: | |
| 111: | |
| 112: | public $formConfig = []; |
| 113: | |
| 114: | |
| 115: | |
| 116: | #[\Override] |
| 117: | protected function init(): void |
| 118: | { |
| 119: | parent::init(); |
| 120: | |
| 121: | $this->formElement = View::addTo($this, ['element' => 'form', 'shortName' => 'form'], ['FormElementOnly']); |
| 122: | |
| 123: | |
| 124: | $this->on( |
| 125: | 'submit', |
| 126: | new JsExpression('if (event.target === this) { event.stopImmediatePropagation(); [] }', [new JsBlock([$this->formElement->js()->trigger('submit')])]), |
| 127: | ['stopPropagation' => false] |
| 128: | ); |
| 129: | |
| 130: | $this->initLayout(); |
| 131: | |
| 132: | |
| 133: | $this->setApiConfig(['stateContext' => $this]); |
| 134: | |
| 135: | $this->cb = JsCallback::addTo($this, [], [['desired_name' => 'submit']]); |
| 136: | } |
| 137: | |
| 138: | protected function initLayout(): void |
| 139: | { |
| 140: | if (!is_object($this->layout)) { |
| 141: | $this->layout = Factory::factory($this->layout ?? [Form\Layout::class]); |
| 142: | } |
| 143: | $this->layout->form = $this; |
| 144: | $this->add($this->layout); |
| 145: | |
| 146: | |
| 147: | if ($this->buttonSave) { |
| 148: | $this->buttonSave = $this->layout->addButton($this->buttonSave); |
| 149: | $this->buttonSave->setAttr('tabindex', 0); |
| 150: | $jsSubmit = $this->js()->form('submit'); |
| 151: | $this->buttonSave->on('click', $jsSubmit); |
| 152: | $this->buttonSave->on('keypress', new JsExpression('if (event.keyCode === 13) { [] }', [new JsBlock([$jsSubmit])])); |
| 153: | } |
| 154: | } |
| 155: | |
| 156: | |
| 157: | |
| 158: | |
| 159: | |
| 160: | |
| 161: | |
| 162: | |
| 163: | public function setControlsDisplayRules($rules = []) |
| 164: | { |
| 165: | $this->controlDisplayRules = $rules; |
| 166: | |
| 167: | return $this; |
| 168: | } |
| 169: | |
| 170: | |
| 171: | |
| 172: | |
| 173: | |
| 174: | |
| 175: | |
| 176: | |
| 177: | |
| 178: | public function setGroupDisplayRules($rules = [], $selector = '.atk-form-group') |
| 179: | { |
| 180: | if (is_object($selector)) { |
| 181: | $selector = '#' . $selector->getHtmlId(); |
| 182: | } |
| 183: | |
| 184: | $this->controlDisplayRules = $rules; |
| 185: | $this->controlDisplaySelector = $selector; |
| 186: | |
| 187: | return $this; |
| 188: | } |
| 189: | |
| 190: | |
| 191: | |
| 192: | |
| 193: | #[\Override] |
| 194: | public function setModel(Model $entity, array $fields = null): void |
| 195: | { |
| 196: | $entity->assertIsEntity(); |
| 197: | |
| 198: | |
| 199: | try { |
| 200: | parent::setModel($entity); |
| 201: | |
| 202: | $this->layout->setModel($entity, $fields); |
| 203: | } catch (Exception $e) { |
| 204: | throw $e->addMoreInfo('model', $entity); |
| 205: | } |
| 206: | } |
| 207: | |
| 208: | |
| 209: | |
| 210: | |
| 211: | |
| 212: | |
| 213: | |
| 214: | |
| 215: | public function onSubmit(\Closure $fx) |
| 216: | { |
| 217: | $this->onHook(self::HOOK_SUBMIT, $fx); |
| 218: | |
| 219: | $this->cb->set(function () { |
| 220: | try { |
| 221: | $this->loadPost(); |
| 222: | |
| 223: | $response = $this->hook(self::HOOK_SUBMIT); |
| 224: | |
| 225: | if (is_array($response) && count($response) === 1) { |
| 226: | $response = reset($response); |
| 227: | } |
| 228: | |
| 229: | return $response; |
| 230: | } catch (ValidationException $e) { |
| 231: | $response = new JsBlock(); |
| 232: | foreach ($e->errors as $field => $error) { |
| 233: | if (!isset($this->controls[$field])) { |
| 234: | throw $e; |
| 235: | } |
| 236: | |
| 237: | $response->addStatement($this->jsError($field, $error)); |
| 238: | } |
| 239: | |
| 240: | return $response; |
| 241: | } |
| 242: | }); |
| 243: | |
| 244: | return $this; |
| 245: | } |
| 246: | |
| 247: | |
| 248: | |
| 249: | |
| 250: | |
| 251: | |
| 252: | public function getControl(string $name): Control |
| 253: | { |
| 254: | return $this->controls[$name]; |
| 255: | } |
| 256: | |
| 257: | |
| 258: | |
| 259: | |
| 260: | |
| 261: | |
| 262: | public function jsError(string $fieldName, $errorMessage): JsExpressionable |
| 263: | { |
| 264: | |
| 265: | if ($this->hookHasCallbacks(self::HOOK_DISPLAY_ERROR)) { |
| 266: | return JsBlock::fromHookResult($this->hook(self::HOOK_DISPLAY_ERROR, [$fieldName, $errorMessage])); |
| 267: | } |
| 268: | |
| 269: | return new JsBlock([$this->js()->form('add prompt', $fieldName, $errorMessage)]); |
| 270: | } |
| 271: | |
| 272: | |
| 273: | |
| 274: | |
| 275: | |
| 276: | |
| 277: | |
| 278: | |
| 279: | public function jsSuccess($success = 'Success', $subHeader = null, bool $useTemplate = true): JsExpressionable |
| 280: | { |
| 281: | $response = null; |
| 282: | |
| 283: | if ($this->hookHasCallbacks(self::HOOK_DISPLAY_SUCCESS)) { |
| 284: | return JsBlock::fromHookResult($this->hook(self::HOOK_DISPLAY_SUCCESS, [$success, $subHeader])); |
| 285: | } |
| 286: | |
| 287: | if ($success instanceof View) { |
| 288: | $response = $success; |
| 289: | } elseif ($useTemplate) { |
| 290: | $responseTemplate = $this->getApp()->loadTemplate($this->successTemplate); |
| 291: | $responseTemplate->set('header', $success); |
| 292: | |
| 293: | if ($subHeader) { |
| 294: | $responseTemplate->set('message', $subHeader); |
| 295: | } else { |
| 296: | $responseTemplate->del('p'); |
| 297: | } |
| 298: | |
| 299: | $response = $this->js()->html($responseTemplate->renderToHtml()); |
| 300: | } else { |
| 301: | $response = new Message([$success, 'type' => 'success', 'icon' => 'check']); |
| 302: | $response->setApp($this->getApp()); |
| 303: | $response->invokeInit(); |
| 304: | $response->text->addParagraph($subHeader); |
| 305: | } |
| 306: | |
| 307: | return $response; |
| 308: | } |
| 309: | |
| 310: | |
| 311: | |
| 312: | |
| 313: | |
| 314: | |
| 315: | |
| 316: | |
| 317: | |
| 318: | |
| 319: | |
| 320: | public function addControl(string $name, $control = [], array $fieldSeed = []): Control |
| 321: | { |
| 322: | return $this->layout->addControl($name, $control, $fieldSeed); |
| 323: | } |
| 324: | |
| 325: | |
| 326: | |
| 327: | |
| 328: | |
| 329: | |
| 330: | public function addHeader($title = null): void |
| 331: | { |
| 332: | $this->layout->addHeader($title); |
| 333: | } |
| 334: | |
| 335: | |
| 336: | |
| 337: | |
| 338: | |
| 339: | |
| 340: | |
| 341: | |
| 342: | public function addGroup($title = null) |
| 343: | { |
| 344: | return $this->layout->addGroup($title); |
| 345: | } |
| 346: | |
| 347: | |
| 348: | |
| 349: | |
| 350: | |
| 351: | |
| 352: | |
| 353: | |
| 354: | |
| 355: | |
| 356: | |
| 357: | |
| 358: | |
| 359: | |
| 360: | |
| 361: | |
| 362: | |
| 363: | public function controlFactory(Field $field, $controlSeed = []): Control |
| 364: | { |
| 365: | $this->model->assertIsEntity($field->getOwner()); |
| 366: | |
| 367: | $fallbackSeed = [Control\Line::class]; |
| 368: | |
| 369: | if ($field->type === 'json' && $field->hasReference()) { |
| 370: | $limit = ($field->getReference() instanceof ContainsMany) ? 0 : 1; |
| 371: | $model = $field->getReference()->refModel($this->model); |
| 372: | $fallbackSeed = [Control\Multiline::class, 'model' => $model, 'rowLimit' => $limit, 'caption' => $model->getModelCaption()]; |
| 373: | } elseif ($field->type !== 'boolean') { |
| 374: | if ($field->enum) { |
| 375: | $fallbackSeed = [Control\Dropdown::class, 'values' => array_combine($field->enum, $field->enum)]; |
| 376: | } elseif ($field->values) { |
| 377: | $fallbackSeed = [Control\Dropdown::class, 'values' => $field->values]; |
| 378: | } elseif ($field->hasReference()) { |
| 379: | $fallbackSeed = [Control\Lookup::class, 'model' => $field->getReference()->refModel($this->model)]; |
| 380: | } |
| 381: | } |
| 382: | |
| 383: | if (isset($field->ui['hint'])) { |
| 384: | $fallbackSeed['hint'] = $field->ui['hint']; |
| 385: | } |
| 386: | |
| 387: | if (isset($field->ui['placeholder'])) { |
| 388: | $fallbackSeed['placeholder'] = $field->ui['placeholder']; |
| 389: | } |
| 390: | |
| 391: | $controlSeed = Factory::mergeSeeds( |
| 392: | $controlSeed, |
| 393: | $field->ui['form'] ?? null, |
| 394: | $this->typeToControl[$field->type] ?? null, |
| 395: | $fallbackSeed |
| 396: | ); |
| 397: | |
| 398: | $defaults = [ |
| 399: | 'form' => $this, |
| 400: | 'entityField' => new EntityFieldPair($this->model, $field->shortName), |
| 401: | 'shortName' => $field->shortName, |
| 402: | ]; |
| 403: | |
| 404: | return Factory::factory($controlSeed, $defaults); |
| 405: | } |
| 406: | |
| 407: | |
| 408: | |
| 409: | |
| 410: | protected array $typeToControl = [ |
| 411: | 'boolean' => [Control\Checkbox::class], |
| 412: | 'text' => [Control\Textarea::class], |
| 413: | 'datetime' => [Control\Calendar::class, 'type' => 'datetime'], |
| 414: | 'date' => [Control\Calendar::class, 'type' => 'date'], |
| 415: | 'time' => [Control\Calendar::class, 'type' => 'time'], |
| 416: | 'atk4_money' => [Control\Money::class], |
| 417: | ]; |
| 418: | |
| 419: | |
| 420: | |
| 421: | |
| 422: | protected function loadPost(): void |
| 423: | { |
| 424: | $postRawData = $this->getApp()->getRequest()->getParsedBody(); |
| 425: | $this->hook(self::HOOK_LOAD_POST, [&$postRawData]); |
| 426: | |
| 427: | $errors = []; |
| 428: | foreach ($this->controls as $k => $control) { |
| 429: | |
| 430: | if (!$control->readOnly && !$control->disabled) { |
| 431: | $postRawValue = $postRawData[$k] ?? null; |
| 432: | if ($postRawValue === null) { |
| 433: | throw (new Exception('Form POST param does not exist')) |
| 434: | ->addMoreInfo('key', $k); |
| 435: | } |
| 436: | |
| 437: | try { |
| 438: | $control->set($this->getApp()->uiPersistence->typecastLoadField($control->entityField->getField(), $postRawValue)); |
| 439: | } catch (\Exception $e) { |
| 440: | if ($e instanceof \ErrorException) { |
| 441: | throw $e; |
| 442: | } |
| 443: | |
| 444: | $messages = []; |
| 445: | do { |
| 446: | $messages[] = $e->getMessage(); |
| 447: | } while (($e = $e->getPrevious()) !== null); |
| 448: | |
| 449: | if (count($messages) >= 2 && $messages[0] === 'Typecast parse error') { |
| 450: | array_shift($messages); |
| 451: | } |
| 452: | |
| 453: | $errors[$k] = implode(': ', $messages); |
| 454: | } |
| 455: | } |
| 456: | } |
| 457: | |
| 458: | if (count($errors) > 0) { |
| 459: | throw new ValidationException($errors); |
| 460: | } |
| 461: | } |
| 462: | |
| 463: | #[\Override] |
| 464: | protected function renderView(): void |
| 465: | { |
| 466: | $this->setupAjaxSubmit(); |
| 467: | if ($this->controlDisplayRules !== []) { |
| 468: | $this->js(true, new JsConditionalForm($this, $this->controlDisplayRules, $this->controlDisplaySelector)); |
| 469: | } |
| 470: | |
| 471: | parent::renderView(); |
| 472: | } |
| 473: | |
| 474: | #[\Override] |
| 475: | protected function renderTemplateToHtml(): string |
| 476: | { |
| 477: | $output = parent::renderTemplateToHtml(); |
| 478: | |
| 479: | return $this->fixOwningFormAttrInRenderedHtml($output); |
| 480: | } |
| 481: | |
| 482: | public function fixOwningFormAttrInRenderedHtml(string $html): string |
| 483: | { |
| 484: | return preg_replace_callback('~<(?:button|fieldset|input|output|select|textarea)(?!\w| form=")~i', function ($matches) { |
| 485: | return $matches[0] . ' form="' . $this->getApp()->encodeHtml($this->formElement->name) . '"'; |
| 486: | }, $html); |
| 487: | } |
| 488: | |
| 489: | |
| 490: | |
| 491: | |
| 492: | |
| 493: | |
| 494: | |
| 495: | |
| 496: | |
| 497: | public function setApiConfig($config) |
| 498: | { |
| 499: | $this->apiConfig = array_merge($this->apiConfig, $config); |
| 500: | |
| 501: | return $this; |
| 502: | } |
| 503: | |
| 504: | |
| 505: | |
| 506: | |
| 507: | |
| 508: | |
| 509: | |
| 510: | |
| 511: | |
| 512: | public function setFormConfig($config) |
| 513: | { |
| 514: | $this->formConfig = array_merge($this->formConfig, $config); |
| 515: | |
| 516: | return $this; |
| 517: | } |
| 518: | |
| 519: | public function setupAjaxSubmit(): void |
| 520: | { |
| 521: | $this->js(true)->form(array_merge([ |
| 522: | 'on' => 'blur', |
| 523: | 'inline' => true, |
| 524: | ], $this->formConfig)); |
| 525: | |
| 526: | $this->formElement->js(true)->api(array_merge([ |
| 527: | 'on' => 'submit', |
| 528: | 'url' => $this->cb->getJsUrl(), |
| 529: | 'method' => 'POST', |
| 530: | 'contentType' => 'application/x-www-form-urlencoded; charset=UTF-8', |
| 531: | 'serializeForm' => true, |
| 532: | ], $this->apiConfig)); |
| 533: | |
| 534: | |
| 535: | |
| 536: | |
| 537: | $this->on('change', '.field input[name], .field textarea[name], .field select[name]', $this->js()->form('remove prompt', new JsExpression('$(this).attr(\'name\')'))); |
| 538: | |
| 539: | if (!$this->canLeave) { |
| 540: | $this->js(true, (new JsChain('atk.formService'))->preventFormLeave($this->name)); |
| 541: | } |
| 542: | } |
| 543: | |
| 544: | |
| 545: | } |
| 546: | |