我对Grav CMS真的很陌生,我试图找出向外部webapi发送请求以传递表单数据的最佳方法。
通常情况下,我会在表单提交后执行PHP代码并向webapi发送请求,在此处阅读问题https://getgrav.org/forum#!/getgrav/general:adding-php-code-in-grav说应该使用插件分隔所有自定义php逻辑。
我是否应该使用插件对外部webapi执行表单发布请求?
我只是想确保我使用插件朝着正确的方向前进。
答案 0 :(得分: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.
}
}