To create a group of SELECTs with a foreach loop in Filament, you need to build the schema dynamically before passing it to the Section::make() method. You cannot use a foreach loop directly within the schema() method's array. Instead, you should create the schema array beforehand and then pass it to the schema() method.
Here's how you can do it:
// First, build the dynamic schema array
$dynamicSchema = [];
foreach ($model->hobbyRatings()->where('parent_id', null)->get() as $rating) {
$dynamicSchema[] = Select::make($rating->tag)
->options(function (Builder $query) use ($rating) {
return $query->where('parent_id', $rating->id)->pluck('name', 'id');
});
}
// Then, create the section with the dynamic schema
$section = Section::make('Ratings')
->schema($dynamicSchema)
->columnSpanFull();
In the above code, we're first iterating over the hobbyRatings and building an array of Select fields. Each Select is configured with its options based on the related ratings. After the loop, we pass the $dynamicSchema array to the Section::make() method.
Regarding your second question about saving certain parts of the form to insert elsewhere, you can create reusable form components or partials. Here's an example of how you might create a reusable address fieldset:
// Create a reusable address fieldset as a function or a class method
function addressFieldset()
{
return [
TextInput::make('address_line_1')->label('Address Line 1'),
TextInput::make('address_line_2')->label('Address Line 2'),
TextInput::make('city')->label('City'),
TextInput::make('state')->label('State'),
TextInput::make('zip')->label('Zip Code'),
// ... other address fields
];
}
// Use the addressFieldset in your form schema
$formSchema = [
// ... other form fields
Section::make('Address Details')
->schema(addressFieldset())
->columnSpanFull(),
// ... other form fields
];
In this example, addressFieldset() is a function that returns an array of form fields related to an address. You can then call this function wherever you need to include the address fields in your form schemas.