Answer the question
In order to leave comments, you need to log in
How to organize the use of the alert widget with pjax?
I'm trying to organize the output of a flash message Alert when using pjax in a widget.
here is the actual code Vidget.php
namespace frontend\widget\vidget;
use yii\base\Widget;
use Yii;
class Videt extends Widget{
public function init(){
parent::init();
}
public function run(){
$model= new Model();
if (Yii::$app->request->post()) {
if($model->save()){
Yii::$app->session->setFlash([
'success',
'Спасибо операция окончена']
);
$this->render('html',[
'model'=>$model
]);
}else{
Yii::$app->session->setFlash([
'error',
'Извините произошла ошибка']
);
$this->render('html',[
'model'=>$model
]);
}
}else{
return $this->render('html',[
'model'=>$model
]);
}
}
views/html.php
use yii\widgets\Pjax;
use yii\bootstrap\Alert;
echo $this->render('_form',[
'model'=>$model,
]);
Pjax::begin(['id' => 'reloded']);
echo Alert::widget();
Pjax::end();
$this->registerJs(
'$("document").ready(function(){
$("#button").on("pjax:end", function() {
$.pjax.reload({container:"#reloded"});
});
});');
?>
_form.php
I don’t write because the form itself works and everything is saved, only after restarting pjax Alert does not work. How to organize it correctly do not tell me?
Answer the question
In order to leave comments, you need to log in
It seems to me that you do not need a widget here, use the standard save method - through the controller action, because widgets are mainly designed to display some parts of the frontend. Also, the code duplication is very large, you render the view 3 times, while you can do all this 1 time after the conditions. It also makes no sense to write something to the session since you are rendering via pjax, you just need to send a message to the view, and there it will be rendered as an alert and you will not need to use the Alert widget.
controller's action:
$message = $status = null;
if (Yii::$app->request->post()) {
if ($model->save()) {
$status = 'success';
$message = 'Спасибо операция окончена';
} else {
$status = 'error';
$message = 'Извините произошла ошибка';
}
}
$this->render('html', [
'model' => $model,
'status' => $status,
'message' => $message,
]);
<?php if ($status !== null && $message !== null): ?>
<div class="alert alert-<?=$status?>">
<strong><?=$status?>!</strong> <?=$message?>
</div>
<?php endif; ?>
.......
.......
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question