Alvartetex
Alvartetex

Reputation: 1

I render wrong the alert widget on yii2

I can´t properly render an alert on yii2 on the index page, im trying to render it on the funcion actionIndex so when i render the indez my query is written and my alert shows up but the alert renders before the index so it shows first the alert and then the index, how can i do it and how can i stablish a duration time to de pop up alert. Thank you this is de code:

 public function actionIndex()
    {
           $numero = Yii::$app->db
                ->createCommand("SELECT cantidad FROM productos WHERE 'nombre' = 'paco'")
                ->queryScalar();
         
         if (($numero) <50){
            echo  Alert::widget([
    'options' => [
        'class' => 'alert',
    ],
    'body' => 'Falta Stock en paco',
                ]);
      }  
         return $this->render('index');  
      
    }

Upvotes: 0

Views: 262

Answers (1)

Asadbek Adashaliyev
Asadbek Adashaliyev

Reputation: 36

Assalomu aleykum, in practice, alerts will be in view files, you should use the following pattern

Controller/method

public function actionIndex()
{
    $numero = Yii::$app->db
        ->createCommand("SELECT cantidad FROM productos WHERE 'nombre' = 'paco'")
        ->queryScalar();

    $alertMessage = null;
    if (($numero) <50){
        $alertMessage = 'Falta Stock en paco';
    }
    return $this->render('index',['alertMessage' => $alertMessage]);
}

View file index.php

<?php
/**
* @var string|null $alertMessage
*/
?>
....
<?php if ($alertMessage): ?>
<?php echo  Alert::widget([
     'options' => [
       'class' => 'alert',
     ],
     'body' => $alertMessage
   ]);
?>
<?php endif; ?>
....

Upvotes: 2

Related Questions