Same exact code on different Fields
Hey, easy question here. I have 3 different fields that have the same exact code in the ->afterStateUpdated(). I always try to follow good practices and not to repeat code, but I'm not sure how to do this. This is how it looks
->afterStateUpdated(function (callable $set, $get) {
$quantity = $get('quantity') == '' ? 1 : $get('quantity');
$width = $get('width') == '' ? 1 : $get('width');
$height = $get('height') == '' ? 1 : $get('height');
if($get('height') == '' or $get('width') == ''){
$set('totalm', 0);
} else {
$set('totalm', bcdiv(((($width * $height) * $quantity)),1,2) );
}
})
And it's exactly the same in 3 different fields. It actually doesn't matter what's inside or the logic around it, I just want to ask if I can write the code just once somewhere and use it where I want. I'm actually not sure because of the $set and $get callables.
3 Replies
You can create a method on the class and pass $get and $set into the method. And return what you need.
Thank you! Can I use another class or do I have to do it in the current extended RelationManager class?
You can do it in any class and call it in any resource. That’s OOP, nothing to do with Filament.