Adding custom Formfields
You can easily add a new Formfield to Voyager. In the example below we will add a number form field (which is already included by default in Voyager).
First we create a new class in our project (it doesn't matter where it is placed) called NumberFormField
1
<?php
2
3
namespace App\FormFields;
4
5
use TCG\Voyager\FormFields\AbstractHandler;
6
7
class NumberFormField extends AbstractHandler
8
{
9
protected $codename = 'number';
10
11
public function createContent($row, $dataType, $dataTypeContent, $options)
12
{
13
return view('formfields.number', [
14
'row' => $row,
15
'options' => $options,
16
'dataType' => $dataType,
17
'dataTypeContent' => $dataTypeContent
18
]);
19
}
20
}
Copied!
The codename variable is used in the dropdown you see in the BREAD builder. In the createContent method we are returning the view that is used to display our form field.
Next, we will create the view specified above.
1
<input type="number"
2
class="form-control"
3
name="{{ $row->field }}"
4
data-name="{{ $row->display_name }}"
5
@if($row->required == 1) required @endif
6
step="any"
7
placeholder="{{ isset($options->placeholder)? old($row->field, $options->placeholder): $row->display_name }}"
8
value="@if(isset($dataTypeContent->{$row->field})){{ old($row->field, $dataTypeContent->{$row->field}) }}@else{{old($row->field)}}@endif">
Copied!
In the view we can add whatever logic we want.
When we are done with our view, we will tell Voyager that we have a new form field. We will do this in a service provider (in the example below we use the AppServiceProvider.
1
<?php
2
3
namespace App\Providers;
4
5
use TCG\Voyager\Facades\Voyager;
6
use App\FormFields\NumberFormField;
7
use Illuminate\Support\ServiceProvider;
8
9
class AppServiceProvider extends ServiceProvider
10
{
11
//..
12
13
public function register()
14
{
15
Voyager::addFormField(NumberFormField::class);
16
}
17
}
Copied!
Last modified 1mo ago
Export as PDF
Copy link