传递参数给控制器 - yii2-app-basic Yii2

Passing Parameter To Controller - yii2-app-basic Yii2

http://localhost/yii2-app-basic/web/site/confirm/39/

我在上部手动传递 39 URL 以了解如何使用参数。

我想在 confirm.php 中显示 39,但它不起作用。我很快就会在 SiteController 控制器的 actionConfirm($id) 中传递 $id。 页面未找到错误即将到来。可能是什么问题。

我刚问了一个问题 ,我在那里得到了答案。但是,现在我被卡住了。

confirm.php

<?php

    /* @var $this yii\web\View */

    use yii\helpers\Html;
    use yii\bootstrap\ActiveForm;
    use yii\captcha\Captcha;
    use yii\bootstrap\Modal;
    use yii\helpers\Url;

    $this->title = 'Contact';
    $this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-about">
    <?echo $id;?>
</div>

SiteController.php

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;

use app\models\LoginForm;
use app\models\ContactForm;
use app\models\EntryForm;
use app\models\RegisterForm;
use app\models\LoginExecForm;
use app\models\ForgotPasswordForm;

class SiteController extends Controller
{
    .
    .
    .
    public function actionConfirm($id)
    {

        $id = Yii::$app->request->get('id');
        return $this->render("confirm",array("id"=>$id));
    }
}

错误来了

如何将 39 从 URL 转到 confirm.php 页。请帮我。原谅我,如果这是一个愚蠢的问题。

你确定你已经启用了

short_open_tag=On

在你的 php.ini?

正确的短代码也是

你也可以看到这个讨论: PHP echo vs PHP short tags

顺便说一句,如果您在此处的函数名称中使用参数 actionConfirm($id) ,则不需要两者都需要,您将有一个必需的参数,该参数由您请求中的 GET 参数设置的参数填充 URL。 你的情况是 /site/confirm/39/

所以要么在函数名中设置它们

public function actionConfirm($id)

或手动获取它们

$id = Yii::$app->request->get('id');

你不需要两者。

但这不是你的问题。您仍然没有在正确的控制器中调用正确的操作。

使用此 urlManager 规则

'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',

您添加的那3个错误请删除。

   '<controller:\w+>/<id:\d+>' => '/view',
   '<controller:\w+>/<action:\w+>/<id:\d+>' => '/',
   '<controller:\w+>/<action:\w+>' => '/',

忘记提及,如果您没有自己的规则,则不要在设置中设置任何规则,那么将使用默认规则来正常处理大部分查询。