Search code examples
phpgrav

How to do a PHP POST to external webapi in Grav CMS?


I'm really new to Grav CMS and I'm trying to figure out the best way to do a post request to an external webapi to pass form data.

Normally I will have PHP Code that gets executed after a form submission and will do a post request to the webapi, reading a question here https://getgrav.org/forum#!/getgrav/general:adding-php-code-in-grav says that should separate all the custom php logic using plugins.

Should I use plugins to do my form post request to the external webapi?

I just want to make sure I'm going in the right direction with plugins.


Solution

  • You can build a plugin for that. Here is a quick sample code, you post your form to the sample page, which is yoursite.com/my-form-route in this example

    <?php
    namespace Grav\Plugin;
    
    use \Grav\Common\Plugin;
    
    class MyAPIPlugin extends Plugin
    {
        public static function getSubscribedEvents()
        {
            return [
                'onPluginsInitialized' => ['onPluginsInitialized', 0]
            ];
        }
    
        public function onPluginsInitialized()
        {
            if ($this->isAdmin())
                return;
    
            $this->enable([
                'onPageInitialized' => ['onPageInitialized', 0],
            ]);
        }
    
        public function onPageInitialized()
        {
            // This route should be set in the plugin's setting instead of hard-code here.
            $myFormRoute = 'my-form-route';
    
            $page = $this->grav['page'];
            $currentPageRoute = $page->route();
    
            // This is not the page containing my form. Skip and render the page as normal.
            if ($myFormRoute != $currentPageRoute)
                return;
    
            // This is page containing my form, check if there is submitted data in $_POST and send it to external API.
            if (!isset($_POST['my_form']))
                return;
    
            // Send $_POST['my_form'] to external API here.
        }
    }