What is the best way to add a custom js file to the backend? I would like to add custom js to the backend for one of my plugins on the modal form. I tried the following code in the Plugin.php file:
public function boot()
{
// Check if we are currently in backend module.
if (!App::runningInBackend()) {
return;
}
// Listen for `backend.page.beforeDisplay` event and inject custom css to current controller instance.
Event::listen('backend.page.beforeDisplay', function($controller, $action, $params) {
$controller->addCss('/themes/mfhl/backend/assets/css/styles.css');
$controller->addJs('/themes/mfhl/backend/assets/js/scripts.js');
});
}
It works when I open a record from the list initially, but when I save and open or create a new record, the js doesn’t work.
I usually add my Custom Css and JS in the Constructor or the index() method of the backend controller.
Not totally sure on the differences between the functions in the moment, I think index() was only called once for ListControllers.
class MyController extends Controller
{
public function __construct()
{
$this->addJs(...);
$this->addCss(...);
}
public function index()
{
$this->addJs(...);
$this->addCss(...);
}
}
Thanks for the reply. I added the js file using public function __construct() and while it loads, I am running into the same issue. If I force refresh, the js loads and works. I save & close, then click on an existing record or create a new one, and the js does not work. I looked at the page code and the js file is there. Just not working and the console isn’t showing any errors. Feels like I am missing something…
Hot Controls will initialize using a traditional page load and a turbo page load. It is also includes a handy disconnect() method for the disposal logic.
Thanks for the suggestions. I disabled turbo mode and it works.
To use Hot Controls, how do I add it to the backend? Create a js file with the hot controls js and add the file via the plugin or controller (as you would with a js file)?
Yes, that’s right, it uses a class pattern to define a control with a name (eg: your-name). Then in HTML it automatically binds to any element with data-control="your-name" defined.