简体   繁体   中英

Magento run custom script on product details page load

I'm pretty new to Magento custom modules and just want to be pointed in the right direction to read up on things.

I'm creating a few websites that I want to have stock dynamically updated from an API (that I'm developing).

Currently I have a script that runs every day to update every product with the current stock count, and another script that gets the difference since the last update and does it (every 10minutes).

I don't like it as there is still room for error and it just doesn't sit right with me. What I would like is as you click on the product, it makes an API call, updates my custom field, and renders the page. I also have a custom stock status plugin so I really need it to do the call before page load. . I can write some logic on timeout to render the page anyway if there is a problem with the API.

Any pointers would be really helpful.

You can use the Event/Observer feature to call the API. Try one of the following events:-

catalog_controller_product_init_before
catalog_controller_product_init_after
catalog_controller_product_view

Got it working... Thanks for your help, there is still some work to do, but its calling the script at the correct time! Thankyou

Events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_controller_product_init_after">
        <observer name="Apicall" instance="Olisco\Tpcconnector\Observer\ApiCall" />
    </event>
</config>


<?php
namespace Olisco\Tpcconnector\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class ApiCall implements ObserverInterface
{

    public function execute(EventObserver $observer)
    {
      #Code here to execute!
    }
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM