FilamentF
Filament‱16mo ago
Alexandre

Incremental itemLabel for repeater

Hello everyone. 👋

I know this question has already been asked several times, but I haven't found any answers...

Basically my question is simple: I'm creating a form with a repeater (questions). In this repeater, I've a second one (answers).
And I want to put an itemLabel in this second repeater with an incremental number (Answer 1, Answer 2, Answer 3, etc.).


Repeater::make('questions')
    ->itemLabel(function () {
        static $position = 1;
        return 'Question n°'.$position++;
    })
    ->schema([
        textInput::make('title')
                ->required(),
        Select::make('need_id')
                ->options(Need::all()->pluck('name', 'id'))
                ->required(),
        Repeater::make('answers')
                ->itemLabel(function ($component, array $state, callable $get) {
                    $answers     = $get('answers');
                    $answerKeys  = array_keys($answers);
                   
                    /*And now, I don't know what to do. How to get the current index of actual answer but without                        uuid ?*/ 

                    return 'Réponse n°';
                })
                ->hiddenLabel()
                ->schema([
                    TextInput::make('title')
                            ->required(),
                    TextInput::make('ratio')
                            ->numeric()
                            ->suffix('%')
                            ->default('20')
                            ->required()
                ])
                ->minItems(5)
                ->maxItems(5)
                ->addActionLabel('Ajouter une réponse')
                ->required()
    ])
    ->minItems(2)
    ->maxItems(4)
    ->addActionLabel('Ajouter une question')
    ->collapsible()


Thanks for you help 😅
Solution
I found a solution on Github for those who are looking too :

->itemLabel(function ($state, $component) {
  $key   = array_search($state, $component->getState());
  $index = array_search($key, array_keys($component->getState()));

  return 'Réponse n°'.$index + 1;
})


And that work like expected đŸ„ł
Source : https://github.com/filamentphp/filament/discussions/8565#discussioncomment-7031649
Was this page helpful?