Best way to inject a third party javascript asset just for one RelationManager form() ?

I have this code in AdminPanelProvider's boot():
FilamentAsset::register([
Js::make('stripe', 'https://js.stripe.com/v3/'),
], 'app');
FilamentAsset::register([
Js::make('stripe', 'https://js.stripe.com/v3/'),
], 'app');
This injects Stripe into my system. However, I only really want to do this where I am actually using Stripe and not on every single page as I do currently. I use the Stripe JavaScript library in one location: app/Filament/Resources/Member/RelationManagers/SubscriptionsRelationManager.php's form() method. The code in form() is:
ViewField::make('payment_method_id')
->columnSpanFull()
->view('forms.components.stripe-card')
->viewData([
'stripeKey' => config('stripe.public_api_key'),
])
->visible(fn (callable $get) => $get('take_payment_now')),
ViewField::make('payment_method_id')
->columnSpanFull()
->view('forms.components.stripe-card')
->viewData([
'stripeKey' => config('stripe.public_api_key'),
])
->visible(fn (callable $get) => $get('take_payment_now')),
The view forms.components.stripe-card contains x-data which utilises the Stripe JavaScript library. Where would you propose I put the inclusion of the Stripe JavaScript library? Thanks.
2 Replies
keiron
keironOP4w ago
Thanks @toeknee , this looks great. I changed my code in AdminPanelProvider to:
FilamentAsset::register([
Js::make('stripe', 'https://js.stripe.com/v3/')
->loadedOnRequest(),
]);
FilamentAsset::register([
Js::make('stripe', 'https://js.stripe.com/v3/')
->loadedOnRequest(),
]);
Unfortunately my x-data code expects Stripe to exist on load of init(), which it doesn't yet. Is there an event that tells me the asset has been registered? I would listen for this event somehow and call my Stripe code within the listener. I solved this by doing:
<div
data-dispatch="stripe-loaded"

x-load-js="[@js(\Filament\Support\Facades\FilamentAsset::getScriptSrc('stripe'))]"

x-on:stripe-loaded-js.window="init_stripe"

x-data="{
stripe: null,
cardElement: null,
modalId: null,
data: null,

init_stripe() { // initialise stripe }"></div>
<div
data-dispatch="stripe-loaded"

x-load-js="[@js(\Filament\Support\Facades\FilamentAsset::getScriptSrc('stripe'))]"

x-on:stripe-loaded-js.window="init_stripe"

x-data="{
stripe: null,
cardElement: null,
modalId: null,
data: null,

init_stripe() { // initialise stripe }"></div>

Did you find this page helpful?