我正在遵循Codeigniter 4.0.4用户指南和创建模块。我已经创建了博客模块,页面加载正确(索引,视图,创建)。
我在创建页面上遇到了麻烦,表单操作调用的是应用程序/控制器,而不是位于应用程序文件夹外的模块控制器。我使用两个助手(表单,网址)。
我的路线
$routes->group('myblog', ['namespace' => 'Acme\MyBlog\Controllers'], function($routes)
{
$routes->get('/', 'MyBlog::index');
$routes->get('view', 'MyBlog::view');
$routes->get('create', 'MyBlog::create');
});我的自动加载
public $psr4 = [
APP_NAMESPACE => APPPATH, // For custom app namespace
'App' => APPPATH,
'Config' => APPPATH.'Config',
'Acme\MyBlog' => ROOTPATH.'Acme\MyBlog'
];我的控制器
<?php namespace Acme\MyBlog\Controllers;
use Acme\MyBlog\Controllers\BaseController;
use Acme\MyBlog\Models\PostModel;
use CodeIgniter\I18n\Time;
class MyBlog extends BaseController
{
public function create()
{
$model = new PostModel();
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required'
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'body' => $this->request->getPost('body'),
]);
echo view('Acme\MyBlog\Views\success');
}
else
{
echo view('Acme\MyBlog\Views\create', ['title' => 'Create a news Post']);
}
}
}我的创建表单
<h2><?= esc($title); ?></h2>
<?= \Config\Services::validation()->listErrors(); ?>
<div>
<div>
<?php echo form_open('myblog/create'); ?>
<?= csrf_field() ?>
<?php echo form_label('What is the Title', 'title');
echo form_input('title') . '<br />';
echo form_label('Post Body', 'body');
echo form_textarea('body') . '<br />';
echo form_submit('submit', 'Create News Post!');
$string = '</div></div>';
echo form_close($string); ?>表单操作被设置为myblog/create,created的html也显示了这一点
// THE HTML CREATED
<div>
<div>
<form action="http://localhost:8080/myblog/create" method="post" accept-charset="utf-8">
<input type="hidden" name="csrf_test_name" value="7b9750243204e5a0578a74cec6b42b77" />
<label for="title">What is the Title</label><input type="text" name="title" value="" />
<br />
<label for="body">Post Body</label><textarea name="body" cols="40" rows="10" ></textarea>
<br />
<input type="submit" name="submit" value="Create News Post!" />
</form>
</div>
</div>然而,当我尝试提交表单时,我得到了以下错误。这个控制器是从哪里调用的?
<div class="wrap">
<h1>404 - File Not Found</h1>
<p>Controller or its method is not found: \App\Controllers\Myblog::create</p>
</div>谢谢你的帮助。
发布于 2021-09-20 14:34:47
您需要将代码从$routes->get('create', 'MyBlog::create');更改为$routes->post('create', 'MyBlog::create');
https://stackoverflow.com/questions/64883246
复制相似问题