Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

marcw's avatar
Level 2

How to keep focus on field when ->afterStateUpdated()

I have a form in a edit/new modal to fill in time entries for timetracking. A duration is calculated after start and end time is entered.

Problem is that when afterStateUpdated fires the focus goes to the closing "x" symbol in the modal. How to keep it on the field?

0 likes
4 replies
LaryAI's avatar
Level 58

To keep the focus on the field when ->afterStateUpdated() is triggered, you can use JavaScript to manually set the focus back to the field. Filament forms provide a way to execute JavaScript after state updates using the ->afterStateUpdated() method.

Here's how you can modify your code to include JavaScript that sets the focus back to the field:

  1. Add an id attribute to the fields you want to keep focused.
  2. Use JavaScript to set the focus back to the field after the state is updated.

Here's an example of how you can achieve this:

In this example, I've added an id attribute to the DatePicker, TimePicker, and other relevant fields. After the state is updated, a small JavaScript snippet is executed to set the focus back to the field using document.getElementById().focus().

This should help keep the focus on the field after the state is updated.

tisuchi's avatar

@marcw I have some random thoughts.

Maybe you can reduce debounce time. e.g.

->reactive()
->debounce(500)

Alternative approach would be using focusOn in the afterStateUpdated. e.g.

->afterStateUpdated(function (callable $set, callable $get) {
    self::updateDuration($set, $get);
    $this->focusOn('ts_time_start'); 
})
marcw's avatar
Level 2

Hi @tisuchi, sorry to answer this late. I missed it. Will give both a try. Thank you.

marcw's avatar
Level 2

Dear @tisuchi I have tried both. Could it be that focusOn is not available?

Please or to participate in this conversation.