-
Notifications
You must be signed in to change notification settings - Fork 2
Value formatters
Value formatters are executed as a sequence and every formatter receives the value that has been returned by the previous one. The first formatter always receives an array with the whole row.
There are three ways to pass a formatter: a Closure that receives the value and returns a value, a Formatter class that implements the Formatter contract or a string which is mapped to a formatter class.
By default this package provides two Formatter classes: YesNoFormatter and ImageFormatter. The are mapped in administr.listview.php config file as yesno and image.
You can pass the formatters as different params or as an array with formatters.
In some cases you might need to change the output value of a given column. Let's imagine that you want to make a ListView that shows the registered users with their avatars.
$users = \App\User::all();
$usersListView = new \Administr\ListView\ListView($users);
$usersListView
->text('id', '#')
->text('avatar', 'Avatar') // this will output the name of the file
->text('name', 'Name')
;Each column accepts three parameters: column name, label and either an array of options or a Closure.
One way to set a value formatter is using the third param and setting a Closure, the other is to set it to the Column instance afterwards.
$usersListView
->text('id', '#')
->text('avatar', 'Avatar', function(Column $column) {
// Like parameters
$column->format(function(array $row) {
return url($row['avatar']);
}, 'image');
// As an array
$column->format([function(array $row) {
return url($row['avatar']);
}, \Administr\ListView\Formatters\ImageFormatter::class]);
})
->text('name', 'Name')
;$usersListView
->text('id', '#')
->text('avatar', 'Avatar')
->text('name', 'Name')
;
$usersListView
->column('avatar')
->define(function(Column $column) {
$column->format(function(array $row) {
return url($row['avatar']);
}, 'image');
})
;class UsersListView extends \Administr\ListView\ListView {
protected function columns()
{
// Either this way
$this
->text('id', '#')
->text('avatar', 'Avatar', function(Column $column) {
$column->format(function(array $row) {
return url($row['avatar']);
}, 'image');
})
->text('name', 'Name')
;
// Or like this
$this
->text('id', '#')
->text('avatar', 'Avatar')
->text('name', 'Name')
;
$this
->column('avatar')
->define(function(Column $column) {
$column->format(function(array $row) {
return url($row['avatar']);
}, 'image');
})
;
}
}