контроллер
public function actionView($id){
...
$model = new BlogForm();
if ($model->load(Yii::$app->request->post()) && $model->post()) {
return $this->refresh();
}
return $this->render('view', [
'model' => $model,
]);
}
модель
class Blog extends ActiveRecord{
public static function tableName(){
return 'blog';
}
public function getCategory(){
return $this->hasOne(Blog::className(), ['id' => 'id']);
}
}
class BlogForm extends Model
{
public $nick ;
public $email;
public $body;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
/* nick and comment body are both required */
[[ 'body'], 'required'],
[['email'], 'email'],
];
}
/**
* Appends post to DB
* @return boolean whether the post is appended successfully
*/
public function post()
{
if ($this->validate()) {
$db = Yii::$app->db;
$nickSafe=Yii::$app->user->identity->email;
$bodySafe = htmlspecialchars($this->body, ENT_QUOTES, "UTF-8");
$db->createCommand('INSERT INTO comments (nick, body)' .
' VALUES (\'' . $nickSafe . '\', REPLACE("' . $bodySafe . '", "\n", "<br />"));')->execute();
return true;
}
return false;
}
}
Представление
<div class="comments">
<p >
<?php Pjax::begin(); ?>
<?php $form = ActiveForm::begin([
'id' => 'post-comment-form',
'options' => ['class' => 'form-horizontal'],
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-1 control-label'],
],
]); ?>
<?php
$field = $form->field($model, 'body', [
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('body'),
],
])->label(false);
$field->textArea([
'rows' => '6'
]);
echo $field;
echo '<div class="form-group">';
echo '<div class="col-lg-11">';
echo Html::submitButton('Отправить', ['class' => 'btn btn-my']);
echo '</div>';
echo '</div>';
?>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</p>
<div class="site-comments">
<h3>Отзывы:</h3>
<?php
$db = Yii::$app->db;
$comments = $db->createCommand('SELECT * FROM comments ORDER BY id DESC;')->queryAll();
?>
<?php
$provider = new ArrayDataProvider([
'allModels' => $comments,
'pagination' => [
'pageSize' => 10,
]
]);
echo ListView::widget([
'dataProvider' => $provider,
'itemView' => function ($model, $key, $index, $widget) {
if ($model['email']) {
return $this->renderDynamic('echo \'<b>' . $model['nick'] . '</b> (' . $model['email'] . '):<br>' . $model['body'] . '<br><br>\';');
} else {
return $this->renderDynamic('echo \'<b>' . $model['nick'] . '</b>:<br>' . $model['body'] . '<br><br>\';');
}
},
'emptyText' => 'Отзывов нет, будьте первым! '
])
?>
</div>
</div>