Sometimes it bothers me to point out many fields to fill out, especially when the same fields are repeated (and this happens quite often), Collections can come to our aid.
Let's try to consider an example:
namespace App\Orchid\Layouts\Client;
use Orchid\Screen\Layouts\Rows;
use Orchid\Screen\Fields\Input;
class ClientEditLayout extends Rows
{
public function fields(): array
{
return [
Field::make('user.name')
->type('text')
->required()
->title(__('Name'))
->placeholder(__('Name')),
Field::make('user.email')
->type('email')
->required()
->title(__('Email'))
->placeholder(__('Email')),
];
}
}
The method for defining fields should return a list of them, and so on every time, why don't we define it only once, by analogy with the model?
namespace App;
use Illuminate\Database\Eloquent\Model;
use Orchid\Screen\Fields\Input;
class Client extends Model
{
/**
* @return \Illuminate\Support\Collection
*/
public static function fields()
{
return collect([
'name' => Input::make('user.name')
->type('text')
->required()
->title(__('Name'))
->placeholder(__('Name')),
'email' => Input::make('user.email')
->type('email')
->required()
->title(__('Email'))
->placeholder(__('Email')),
]);
}
}
We created a static method that will return a collection of our fields to us, but with the addition of keys, this will help us, in cases where it is necessary to display only a part of the properties, for this we will use the capabilities of the collections.
All available fields:
namespace App\Orchid\Layouts\Client;
use App\Client;
use Orchid\Screen\Fields\Input;
class ClientEditLayout extends Rows
{
public function fields(): array
{
return Client::fields()->all();
}
}
Return only the specified ones:
namespace App\Orchid\Layouts\Client;
use App\Client;
use Orchid\Screen\Fields\Input;
class ClientEditLayout extends Rows
{
public function fields(): array
{
return Client::fields()->only([
'email',
])->toArray();
}
}
Return everything except the specified ones:
namespace App\Orchid\Layouts\Client;
use App\Client;
use Orchid\Screen\Fields\Input;
class ClientEditLayout extends Rows
{
public function fields(): array
{
return Client::fields()->except([
'email',
])->toArray();
}
}
And so on, such simple examples may not duplicate field descriptions every time it is required.