How do you add JS assets to a BackEnd formWidget in Child Form in OctoberCMS?

471 Views Asked by At

I am not sure if I am adding my JS assets correctly and would like some advice if I am not.

In octoberCMS I have created a custom formWidget that uses the Google Maps API.

I am using my formWidget inside a child form that is rendered via AJaX as a modal when required.

If I use the following code in my widget class:

public function loadAssets(){
    $this->addJs("http://maps.googleapis.com/maps/api/js?key=myappkeyhere&libraries=places");
    $this->addJs('js/geocomplete/jquery.geocomplete.min.js');
    $this->addJs('js/addressinput.js');
    $this->addCss('css/addressinput.css');
}

The JS loads with the Page load and not when the widget is rendered. This produces these issues:

  1. The google-maps API returns an error saying it has been loaded multiple times.
  2. Events tied to DOM elements in the child fail since the elements are not in the DOM until the form is called.

The workaround I am using is to embed my JS into the formWidget partial.

Is there a way to make the addJS method work for the formWidget when it is part of a child form?

1

There are 1 best solutions below

0
On

After some investigation, I realised that my formWidget using the addJs() method would make the widget JS available globally to the entire page even before the formWidget existed or was even needed.

While I could have created an elaborate, fancy JS involving listeners for DOM insertions and blah blah blah, this was not ideal (mainly because the widget properties change based on implementation).

The quickest/safest way to include JS that is tightly bound to a complex formWidget is to include it in the partial. This ensures the form widget will work properly both in a standalone form and in situations where the widget is part of child form that is created via an Ajax load.

(If you know of a better way please let me know)