Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion src/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Uniform;

use Kirby\Http\Url;
use ErrorException;
use Kirby\Toolkit\Str;
use Kirby\Http\Response;
use Uniform\Guards\Guard;
Expand Down Expand Up @@ -68,6 +67,17 @@ class Form extends BaseForm
*/
protected $success;

/**
* Hooks to be executed in different stages of form processing
*
* @var array
*/
protected $hooks = [
'success' => [],
'error' => [],
'always' => [],
];

/**
* Create a new instance
*
Expand Down Expand Up @@ -209,13 +219,39 @@ public function action($action, $options = [])
return $this;
}

/**
* Register a hook
*
* @throws Exception If the hook event does not exist
*
* @param string $hook Hook event
* @param callable $callback Hook callback
* @return Form
*/
public function on(string $event, callable $fn): Form
{
if (! in_array($event, array_keys($this->hooks))) {
throw new Exception("Hook event '{$event}' does not exist.");
}

$this->hooks[$event][] = $fn;
return $this;
}

/**
* Redirect back (after actions have been performed).
*/
public function done()
{
$this->flash->set(self::FLASH_KEY_SUCCESS, $this->success);

foreach ($this->hooks[$this->success ? 'success' : 'error'] as $hook) {
$hook($this);
}
foreach ($this->hooks['always'] as $hook) {
$hook($this);
}

if ($this->shouldRedirect) {
die(Response::redirect(Url::last()));
} else {
Expand Down