WordPress Form Field Validation To TypeRocket Controllers
In the previous tutorial, we covered creating a custom flight controller and forms. Let's extend the forms with field validation.
Add Validation
Start by adding form field validation to the \App\Controllers\FlightController
's create
and update
methods. You can add validation to forms in a few ways using the validator TypeRocket comes with. In this tutoral, we will instead use the \TypeRocket\Http\Fields
class. The \TypeRocket\Http\Fields
class makes use of the validator but adds a few extra features to simplify the process of applying validation on a page request.
To create a custom \TypeRocket\Http\Fields
class use the galaxy CLI.
php galaxy makes:fields FlightFields
Now, open the FlightFields
under app/Http/Fields/FlightFields.php
. Make the notes
field required and set $run
to true
.
<?php
namespace App\Http\Fields;
use TypeRocket\Http\Fields;
class FlightFields extends Fields
{
/** @var bool Validate & redirect on errors immediately */
protected $run = true;
/**
* @return array
*/
protected function fillable() {
return [];
}
/**
* @return array
*/
protected function rules() {
return [
'notes' => 'required'
];
}
}
Apply Validation
Now, just import the new FlightFields
into the create
and update
methods. Note, that we replace Request
with FlightFields
because we only need the fields and nothing else from the request.
public function create(\App\Http\Fields\FlightFields $fields, Flight $flight, Response $response)
{
if(!$flight->can('create')) {
$response->unauthorized('Unauthorized: Flight not created')->abort();
}
$flight->save($fields);
return tr_redirect()->toPage('flight','index')->withFlash('Flight created!');
}
public function update(Flight $flight, \App\Http\Fields\FlightFields $fields, Response $response)
{
if(!$flight->can('update')) {
$response->unauthorized('Unauthorized: Flight not updated')->abort();
}
$flight->save($fields);
return tr_redirect()->toPage('flight','edit', $flight->getID())->withFlash('Flight updated!');
}
Now, when there is a field input error the user will be redirected back to the previous page and get shown an error message.
Keeping Old Fields and Showing Field Errors
Next, in the add
and edit
methods apply the errors, useErrors()
, to the forms and keep the old fields, useOld()
.
public function add()
{
$form = tr_form(Flight::class)->useErrors()->useOld();
$button = 'Add';
return tr_view('flights.form', compact('form', 'button'));
}
public function edit(Flight $flight)
{
$form = tr_form($flight)->useErrors()->useOld();
$button = 'Update';
return tr_view('flights.form', compact('form', 'button'));
}
Next, in the views/flights/form.php
file apply a required asterisk to the notes field.
$form->editor('Notes')->markLabelRequired()
Finished!