symfonyshopwareshopware6shopware6-api

how to call the service(php class) function when clicked on the button on Shopware administration


I’m new in Shopware6 I’m creating a plugin in which I have created the child menu inside the catalog as an importer and when the user clicks on importer menu it takes the user to a new import page where I showed the button as an import and I want to run one of my service (php class) function when clicking on the import button, see the screenshot

Screenshot

I want the sample code to accomplish my problem


Solution

  • If you haven't done so already, create an admin API route with an endpoint that will execute your code. The procedure is the same as adding a store API route but you replace store-api in the route scope and path with just api.

    Then in your admin component you can request the endpoint with proper authorization like that, depending on the method used for your route:

    const initContainer = Shopware.Application.getContainer('init');
    const headers = {
        Accept: 'application/vnd.api+json',
        Authorization: `Bearer ${Shopware.Service(
            'loginService'
        ).getToken()}`,
        'Content-Type': 'application/json',
    };
    
    const endpoint = 'api/my/custom/endpoint';
    initContainer.httpClient.get(endpoint, { headers });
    initContainer.httpClient.post(endpoint, { someParam: true }, { headers });
    initContainer.httpClient.patch(endpoint, { someParam: true }, { headers });
    initContainer.httpClient.delete(endpoint, { data: { id: '...' }, headers });