skip to Main Content

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([
        FormsComponentsSelect::make('quiz_id')
            ->options(Quiz::all()->pluck('name', 'id'))
            ->required(),
        FormsComponentsRichEditor::make('steps')
            ->toolbarButtons([
                'bold',
                'bulletList',
                'italic',
                'link',
                'orderedList',
                'redo',
                'undo',
            ]),
        FormsComponentsRichEditor::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?

2

Answers


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

    use FilamentFormsComponentsRepeater;
    use FilamentFormsComponentsSelect;
    use FilamentFormsComponentsTextInput;
     
    Repeater::make('members')
        ->schema([
            TextInput::make('name')->required(),
            Select::make('role')
                ->options([
                    'member' => 'Member',
                    'administrator' => 'Administrator',
                    'owner' => 'Owner',
                ])
                ->required(),
        ])
        ->columns(2)
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search