Access parent component value from the Repeater in Filament

rmitesh

Mitesh Rathod

Posted on March 27, 2024

Access parent component value from the Repeater in Filament

If you want to interact with fields outside of Repeater input, then you can use use $get('../../parent_field_name').

Yes, $get is very powerful function.

Let's say you have few Fields in the form - Order fields.


<?php

use App\Models\Product;
use Filament\Forms;
use Filament\Forms\Form;

public static function form(Form $form): Form
{
    return $form
        ->schema([
            Forms\Components\TextInput::make('order_number')
                ->label('Order Number')
                ->placeholder('Order Number')
                ->maxLength(20)
                ->required(),

            Forms\Components\Repeater::make('products')
                ->relationship()
                ->schema([
                    Forms\Components\TextInput::make('product_code')
                        ->label('Product Code')
                        ->required(),

                    Forms\Components\Select::make('product_id')
                        ->label('Product')
                        ->options(Product::query()->pluck('name', 'id'))
                        ->required()
                        ->reactive()
                        ->afterStateUpdated(fn ($state, Forms\Set $set) =>
                            $set('price', Product::find($state)?->retail_price ?? 0)
                        )
                        ->distinct()
                        ->disableOptionsWhenSelectedInSiblingRepeaterItems()
                        ->searchable(),

                    Forms\Components\TextInput::make('quantity')
                        ->label('Quantity')
                        ->numeric()
                        ->default(1)
                        ->required(),

                    Forms\Components\TextInput::make('price')
                        ->label('Unit Price')
                        ->disabled()
                        ->numeric()
                        ->required(),
                ]),
        ]);
}
Enter fullscreen mode Exit fullscreen mode

Now, you want to access the order number in the product repeater, you can do with


Forms\Components\TextInput::make('product_code')
    ->label('Product Code')
    ->required()
    ->afterStateUpdated(function(Forms\Get $get) {
        return $get('../../order_number'); // using .. you can access parent component value. same as directory structure.
    }),

Enter fullscreen mode Exit fullscreen mode

For more details you can refer the Filament doc for the same.

and there you go!..

💖 💪 🙅 🚩
rmitesh
Mitesh Rathod

Posted on March 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related