0

我对 Grav CMS 真的很陌生,我正在尝试找出向外部 webapi 发出发布请求以传递表单数据的最佳方法。

通常,我将在表单提交后执行 PHP 代码,并向 webapi 发出发布请求,在此处阅读问题https://getgrav.org/forum#!/getgrav/general:adding-php-code-in -grav表示应该使用插件分离所有自定义 php 逻辑。

我应该使用插件向外部 webapi 发送表单发布请求吗?

我只是想确保我在使用插件方面朝着正确的方向前进。

4

1 回答 1

0

您可以为此构建一个插件。这是一个快速示例代码,您将表单发布到示例页面,yoursite.com/my-form-route在此示例中

<?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.
    }
}
于 2017-08-19T08:08:44.560 回答