簡體   English   中英

如何在 PHP Plates 模板引擎上顯示錯誤

[英]How to display error on PHP Plates templating engine

我正在嘗試為我的一個項目設置platesphp

模型中的一種方法檢查新用戶提供的電子郵件地址,並判斷他們嘗試使用的電子郵件是否存在。

就像是

class UserModel extends BaseModel
{
    public $errors = [];

    public function validate()
    {
        if (filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) === false) {
            $this->errors[] = 'Invalid email';
        }
        if ($this->emailExists($this->request->post['email'])) {
            $this->errors[] = 'Email already exist';
        }
    }

    protected function emailExists($email)
    {
        $sql = 'SELECT * FROM user_account WHERE email = :email';
        -----
        -----
        $stmt->execute();
        return $stmt->fetch() !== false;
    }
}

並在控制器中

public function register()
{
    $this->load->getModel('UserModel');

    if ($this->model_UserModel->registerUser($this->request->post)) {
        echo "Success ... load (redirect) second page";
    } else {
        $data ['error'] = $this->model_UserModel->errors;
        echo $this->template->render('home/home', $data);
    }
}

如果電子郵件存在並且我 var dump $data ['error'] 它會顯示“電子郵件已經存在”,如 UserModel 中的驗證方法中所定義。

現在,我試圖通過在 tpl 文件中添加這些行來獲取我的主頁模板上的錯誤消息

<?php if (!empty($this->e($errors))): ?>
    <?php foreach($errors as $error): ?>
        <li><?=$this->e($error)?></li>
    <?php endforeach ?>
<?php endif;?>

但是現在如果我點擊注冊頁面模板說

注意:未定義變量:第 14 行 C:\\xampp\\htdocs\\vem\\App\\Views\\template\\register\\registeruser.tpl 中的錯誤

我該如何前進?

我什至嘗試設置$this->e($error) = ''但 naa,顯示另一個錯誤。

在您的控制器上,您正在設置變量error ,但在模板中,您正在訪問變量errors (使用s )。 試試

<?php if (@$error)): ?>
    <?php foreach($error as $e): ?>
        <li><?=$this->e($e)?></li>
    <?php endforeach ?>
<?php endif;?>

您需要使用error而不是errors

<?php if (!empty($this->e($error))): ?>
    <?php foreach($error as $error_item): ?>
        <li><?=$this->e($error_item)?></li>
    <?php endforeach ?>
<?php endif;?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM