Skip to main content

Field Actions

Fields may define actions which can be called from the front-end. These action do not require a route, controller or a custom axios call.

Getting started

Let's start by adding an arbitrary action in our field:

class Example extends Field
{
public function __construct(string $label, string $name, string $otherResource = null)
{
parent::__construct($label, $name, $otherResource);

$this->addAction('doApiCall', function (ManagesForm $form, $args, FieldActionResponseConstructor $responseConstructor) {
return $responseConstructor->success(
$this->doSomeApiCallWithId($args[0])
);
});
}
}

Within the action you will get access to the current state of the form. You can call methods on this form:

$form->setFieldMeta('some_field', 'some_key', 'some_value');

$form->setState('some_field', 'some_value');

$form->showFields('some_hidden_field');

Usage

We can call our doApiCall action in the front-end from the Field trait:

fields/Example/Field.vue
<template>
<q-input
v-model="value"
...
>
<template v-slot:append>
<q-btn
@click="callAction('doApiCall', 10)"
:loading="loading"
rounded
:label="$t('Do api call')"
>
</q-btn>
</template>
</q-input>
</template>

<script>
import Field from 'qore/mixins/resource/Field'

export default {
mixins: [Field],
...
}
</script>

Getting data from the action

Field actions can return data that will be present in your fields component data after it ran. It will be found under the actions.ACTION_NAME key inside your data.

Example:

$this->addAction('do_something', function (ManagesForm $form, array $args) {
return 'action called';
});
<template>
{{ data.actions.do_something }}
<!-- Will first be undefined, but then will be changed to 'action called' after the action is ran -->
</template>

To standardize the responses from actions across multiple projects you get injected a response constructor.

$this->addAction('do_something', function (ManagesForm $form, array $args, FieldActionResponseConstructor $response) {
if ($error) {
return $response->fail('Fail reason', $moreDataToBeUsedInCaseOfFail);
}

return $response->success($data);
});
<template>
{{ data.actions.do_something }}
<!-- { error: false|true, error_message: string|null, data: YOUR_DATA } -->
</template>