Triggering JS Code in the External File via Button Layout Component

With the help of this tutorial, you'll learn how to connect your JavaScript code created in a separate JS file and call it in a Button Layout Component handler — which gets triggered when you click that button. Keep reading and find out what to do. 

When to Use 

Suppose you have a lot of JS logic that needs to trigger when you click a Button Layout Component in Pimcore Admin. If you had just a few lines of code, then it would look good even if you just pasted them into the Handler input field, but if the logic is complex, you might want to call a single function that will handle everything.

Step-by-Step Solution

First, we need to create our JS file where our logic will be and connect it to an Event Listener so it is loaded when the Pimcore starts. You can refer to our older tutorial for a guide on how to do this. In that guide's first few steps, we explained how to do precisely that.

Now that we have a place for our JS code ready, let's see what the Button Layout Component looks like. We added one to our class by right-clicking it, and choosing Add Layout Component -> Button, like this:

 

Adding layout component

 

When you add it, it will look like this:

 

Pimcore button handler

 

You can see that we already got the suggestion for our handler function from Pimcore. Since we don't want to have much code here, we want to call a single function. Let's do that by utilizing the window object.

 

 

Here we created the pimcoreButtonClickEvents object that can hold all of our click functions for different buttons. We also created a simple function testClickEvent, that will show an alert on click.

In order to trigger that function on click, we need to call it inside the button Handler, as is displayed below:

 

Handler function

 

With this, we now have access in our function to both the button component and its container component, so we can find their IDs, configuration, and everything else we might need to know about them.

Time for Testing

To test it, we can go to an object of the appropriate class (inside which we created this button), and when we click the button, we should see the Hello world! alert. After that, we are ready to start writing the actual logic of the event.

 

Do you have more questions or issues while implementing this? Reach out to us; we'll be happy to help!

 

Looking for Exponential Growth? Let’s Get Started.
Explore next

Pimcore Tutorial

Check out our step-by-step tutorials on how to use Pimcore features and solutions.

Discover more