Adding fields to page
It is very common to have a form on your page. You can make use of fields on your custom page as described below.
Getting started
Let's create a Profile page for the logged in user:
<template>
<q-page class="q-pa-md">
<q-card>
<q-card-section>
<div class="text-h6">
{{$t('Profile')}}
</div>
</q-card-section>
<q-card-section>
<base-form
endpoint="profile"
method="PUT"
/>
</q-card-section>
</q-card>
</q-page>
</template>
<script>
export default {}
</script>
As you can see, there is a base-form
component included.
See more info about BaseForm here: The BaseForm
Adding fields
The base-form
has a endpoint
to profile
.
This means it will retrieve field information from this url, but also uses this url to submit the form.
Let's add the routes:
Route::get('profile', [ProfileController::class, 'updateProfileForm']);
Route::put('profile', [ProfileController::class, 'updateProfile']);
And the controller:
class ProfileController extends Controller
{
use HasFields;
public function updateProfileForm(): JsonResponse
{
return $this->fieldsResponse($this->fields());
}
public function updateProfile(Request $request): JsonResponse
{
$this->validateFields($request, $this->fields());
$user = auth()->user();
$user->update([
'name' => $request->name
]);
return response()->json([
'message' => 'ok'
]);
}
private function fields(): FieldCollection
{
return new FieldCollection(
Text::make(__('Name'), 'name')->default(auth()->user()->name)
->setMaxWidth('sm')
->rules('required')
);
}
}
The HasFields trait
Including the HasFields
trait makes it possible to:
- Send a response that communicates with the
BaseForm
usingreturn $this->fieldsResponse($this->fields());
- Validate user input using
$this->validateFields($request, $this->fields())
Fields response
In the example above, fields are returned back in the response:
public function updateProfileForm(): JsonResponse
{
return $this->fieldsResponse($this->fields());
}
Aside from fields, there are multiple other options that can be returned in the response:
$this->fieldsResponse(
$this->fields(), // The field collection
$myModel, // The model that is related to the form state
[ // Additional response data,
'Some' => 'Additional response data'
],
(new FieldLayout()) // Field layout
->column('name')
->column('type'),
true, // Whether to use the model to initialize the form state
function (ManagesForm $form) { // Callback when the form is ready
if ($form->getModel()) {
$form->setSubmitButtonLabel('Update user');
} else {
$form->setSubmitButtonLabel('Create user');
}
}
);