0

I have a form in my Filament resource and for each textarea I would like to create a new record. I can't figure out how to do this.

The form:

return $form
    ->schema([
        Forms\Components\Select::make('quiz_id')
            ->options(Quiz::all()->pluck('name', 'id'))
            ->required(),
        Forms\Components\RichEditor::make('steps')
            ->toolbarButtons([
                'bold',
                'bulletList',
                'italic',
                'link',
                'orderedList',
                'redo',
                'undo',
            ]),
        Forms\Components\RichEditor::make('goal')
            ->toolbarButtons([
                'bold',
                'bulletList',
                'italic',
                'link',
                'orderedList',
                'redo',
                'undo',
            ]),
    ]);

Upon creation / edit I would like to insert a record for each richEditor:

  • id, quiz_id, field_name, value
  • id, quiz_id, field_name, value
  • id, quiz_id, field_name, value
  • ...

I was looking at the function handleRecordCreation in my createRecord class but I can't figure out how to return.

This code manages to store the records as I want but it must return a Model

protected function handleRecordCreation(array $data): FeedbackReport
{
    foreach ($data as $field_name => $value) {
        if ($field_name != 'quiz_id') {
            $record = array(
                'quiz_id' => $data['quiz_id'],
                'field_name' => $field_name,
                'value' => $value,
            );
            static::getModel()::create($record);
        }
    }
}

Any ideas? Or do I need a totaly different approach for this?

Tim Reynaert
  • 145
  • 5
  • 19

2 Answers2

0

I think the way you are approaching the problem is wrong. I would suggest using a repeater field.

use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
 
Repeater::make('members')
    ->schema([
        TextInput::make('name')->required(),
        Select::make('role')
            ->options([
                'member' => 'Member',
                'administrator' => 'Administrator',
                'owner' => 'Owner',
            ])
            ->required(),
    ])
    ->columns(2)
0

This is how I have done it

protected function handleRecordCreation(array $data): Model
    {
        $userIds = $data["user_id"];
        unset($data["user_id"]);

        $models = [];

        foreach ($userIds as $index => $userId) {
            $data['user_id'] = $userId;
            $model = static::getModel()::create($data);
            $models[] = $model;
        }

        return $models[0];
    }

Works for my case.

StealthTrails
  • 2,281
  • 8
  • 43
  • 67