我如何将图像插入验证消息? (Yii2)

时间:2015-09-24 14:19:32

标签: yii2

我写

[['section'], 'required', 'message' => '<span><img src="http://troll-face.ru/static/mememaker/c/6/19423-gaechka.jpg">Вы не выбрали раздел!</span>']

在规则中,但它以文本形式输出,而不是图像。 输出图像是不可能的? 谢谢。

1 个答案:

答案 0 :(得分:1)

以下是advanced template的客户端和服务器端验证的工作示例

<强> /frontend/assets/AppAsset.php

<?php

namespace frontend\assets;

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{        
    public $depends = [
        'yii\bootstrap\BootstrapAsset',        
    ];
}

<强> /frontend/controllers/DummyController.php

<?php

namespace frontend\controllers;

use frontend\models\Dummy;
use yii\web\Controller;

class DummyController extends Controller
{
    public function actionIndex()
    {
        $this->layout = 'dummy';
        $model = new Dummy();
        if ($model->load(\Yii::$app->getRequest()->post()) === true) {
            $model->validate();
        }
        return $this->render('index', compact('model'));
    }
}

<强> /frontend/models/Dummy.php

<?php

namespace frontend\models;

use yii\base\Model;

class Dummy extends Model
{
    public $name;

    public function rules()
    {
        return [
            [['name'], 'required', 'message' => '
                <span>
                    <img src="http://troll-face.ru/static/mememaker/c/6/19423-gaechka.jpg">
                    Вы не выбрали раздел!
                </span>
               '
            ],
        ];
    }

    public function attributeLabels()
    {
        return [
            'name' => 'Name',
        ];
    }
}

<强> /frontend/views/dummy/index.php

<?php

/**
 * @var $this yii\web\View
 * @var $form yii\widgets\ActiveForm
 * @var $model frontend\models\Dummy
 */

use yii\widgets\ActiveForm;
use yii\helpers\Html;

$form = ActiveForm::begin();
echo $form
    ->field($model, 'name', [
        'errorOptions' => [
            'tag' => 'div',
            'class' => 'help-block',
            'encode' => false
        ]
    ]);
echo Html::submitButton('Submit');
ActiveForm::end();

<强> /frontend/views/layouts/dummy.php

<?php

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

?>

<?php

use frontend\assets\AppAsset;
use yii\helpers\Html;

AppAsset::register($this);

?>

<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?php echo Html::encode(Yii::$app->language) ?>">
<head>
    <?php
    $this->head();
    echo Html::tag('title', sprintf('%s, %s', Yii::$app->id, Html::encode($this->title)));
    ?>
</head>
<body>
<?php
$this->beginBody();
echo $content;
$this->endBody();
?>
</body>
</html>
<?php $this->endPage() ?>