Skip to main content

Form interceptions

Sometimes you need to do something before a resource gets created or updated, and inform the user about it.

For example, when updating an organization, you might show a message that asks the user if sibling organizations should be updated too.

Usage

To start using interceptions, we need to add 2 methods to our resource:

// Whether the request should be intercepted
public function shouldIntercept(array $state, ?Model $model = null): bool
{
// Usually you would check if something is missing inside `state` here
return true;
}
use Qore\System\Http\Resource\SubmitInterceptor;

// What we want to do in our interception
public function onFormSubmit(SubmitInterceptor $interceptor): SubmitInterceptor
{
return $interceptor;
}

Now when you submit your form, a modal will open (every time, since it always returns true).

API

Should intercept

If you want to intercept only once you can check the following:

public function shouldIntercept(array $state, ?Model $model = null): bool
{
return !isset($state['was_intercepted']);
}

This value will be inside the state when the user presses Ok or Reject

On Form Submit

The following can be chained on the SubmitInterceptor. Everything is optional.

public function onFormSubmit(SubmitInterceptor $interceptor): SubmitInterceptor
{
// Optionally check if we're creating or updating a model:
if ($interceptor->isCreating()) { ... }
if ($interceptor->isUpdating()) { ... }

return $interceptor
// The message
->message(__('My custom message'))

// Icon
->icon('business')
->iconColor('negative')

// Confirm button
->confirmButtonText(__('Confirm button'))
->confirmButtonColor('primary')

// Add a reject button
->rejectable()
->rejectButtonText(__('Reject button'))
->rejectButtonColor('negative')

// Dialog size
->setWidth(600) // width in pixels (width: 600px)
->setMaxWidth(90) // maximum view width (max-width: 90vw)

// Fields
->fields(function(array $state, ?Model $model = null) {
// In $state you can find the full form state of the related resource
return new FieldCollection(
Text::make('Project naam', 'project_name')
->rules('required')
->default('Some value')
);
})

// Callback that is called after the resource has fully updated/created
->then(function(Model $model, array $state, bool $wasRejected) {
if (!$rejected) {
$model->projects()->create(['name' => $state['project_name']]);
}
});
}