Dynamically Populate Batch Number Select Based on Product Selection in Filament

Hi everyone,👋 I’m trying to populate a Select field for batch_number based on the selected product_id in Filament. I want the batch_number select to be dynamically updated after a product is chosen. Here’s the code I’m working with:
Select::make('product_id')
->live()
->translateLabel()
->options(function(){
return Product::pluck('name','id');
})
->required()
->afterStateUpdated(function(string $state, Set $set){
// Get the selected product
$product = ProductService::fromId($state);
// Generate options for the batch_number select
$optionsForBatchNumberSelect = $product->getWarehouses()->pluck('batch_number','id');

// Set the batch_number select with the generated options
$set('batch_number', $optionsForBatchNumberSelect->toArray());
}),

Select::make('batch_number')
->live();
Select::make('product_id')
->live()
->translateLabel()
->options(function(){
return Product::pluck('name','id');
})
->required()
->afterStateUpdated(function(string $state, Set $set){
// Get the selected product
$product = ProductService::fromId($state);
// Generate options for the batch_number select
$optionsForBatchNumberSelect = $product->getWarehouses()->pluck('batch_number','id');

// Set the batch_number select with the generated options
$set('batch_number', $optionsForBatchNumberSelect->toArray());
}),

Select::make('batch_number')
->live();
The issue is that the batch_number select isn't being populated after the product is selected. What am I missing or doing wrong? How can I make the batch_number field update dynamically based on the product selection? this is the value of the variable $optionsForBatchNumberSelect->toArray():
array:3 [▼ // app/Filament/Resources/WarehouseTransferResource.php:85
1 => "499104"
13 => "499104"
14 => "221"
]
array:3 [▼ // app/Filament/Resources/WarehouseTransferResource.php:85
1 => "499104"
13 => "499104"
14 => "221"
]
No description
No description
3 Replies
Daniel
Daniel5d ago
GitHub
Add state of field to an array to use in select options · filamentp...
I have this: TextInput::make('step_field_name') ->label('Field Name') ->live() ->afterStateUpdated(function (string $state) { $field_names[] = $state; }) and trying to pass...
toeknee
toeknee5d ago
Your setting sets the values i.e. defaults, you need to get the options based on the parent select i.e. product_id
Select::make('batch_number')
->live();
Select::make('batch_number')
->live();
to
Select::make('batch_number')
->options(fn($get) => ProductService::fromId($get('product_id')->getWarehouses()->pluck('batch_number','id'))
->live();
Select::make('batch_number')
->options(fn($get) => ProductService::fromId($get('product_id')->getWarehouses()->pluck('batch_number','id'))
->live();
Want results from more Discord servers?
Add your server