Trigger state format when reciving new state from afterStateUpdated with $set from another field?

If you have a field like this: TextInput::make('price_to') ->live() ->label('Price To') ->debounce(500) ->afterStateUpdated(function (Set $set, $state) { $set('price', $state); }), TextInput::make('price') ->label('Price') ->default(123) ->formatStateUsing(....), Is there a way to trigger a new format of the received state on the price field after it has been updated from the price_to fields afterStateUpdated?
Solution:
You could just extract the formatter to an str macro or helper function then you don’t have to repeat it. Also, iirc, formatStateUsing() only runs during the form initialization so it doesn’t run on updates through get / set which manipulates the livewire data directly....
Jump to solution
5 Replies
Lara Zeus
Lara Zeus7d ago
its should be possible, try adding live to price?
awcodes
awcodes7d ago
When you $set price it has no context of the update. FormatState doesn’t run on updating the value, so you would have to format it before setting the value.
pelmer
pelmerOP6d ago
Yes, that is what I was doing. But that means duplicating the formatting code. I also think each field should be responsible for their own formatting. I think it would be a good improvement if formatStateUsing or afterStateUpdate was triggered in this case. Or at least some event or something that you can hook into.
Solution
awcodes
awcodes6d ago
You could just extract the formatter to an str macro or helper function then you don’t have to repeat it. Also, iirc, formatStateUsing() only runs during the form initialization so it doesn’t run on updates through get / set which manipulates the livewire data directly.
pelmer
pelmerOP2d ago
Yes, that is what I am doing now. I was hoping there was a better way to handle this in the field that receives the updated state. I think the responsibility of formatting the state should be on the field, not the code that updates the state of the field. Thank you anyway ❤️

Did you find this page helpful?