Yii 2 FAQ

Next I’m using a foreach loop to do something with each question and it’s corresponding id. In this case, the something is first creating a url that has $id as a parameter. Then I’m echoing out each line, using the Html::a mehtod to create a link that uses $question as the link text and $url as the url to the view.

So that will send a request to the view action on the frontend faq controller:


public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

It takes in the $id from the get variable, which was set in the url, and calls an instance of the view, using the correct instance of the model by using the last method on the controller:


   protected function findModel($id)
    {
        if (($model = Faq::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

Then in frontend\views\faq\view.php, we have:


<?php
  use yii\helpers\Html;
    $this->title = 'FAQ: '. $model->question;
    
$this->params['breadcrumbs'][] = ['label' => 'FAQ', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>


    </br>
 <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">
                     <h1>   <?= $model->question;?> </h1>
                    </h3>
                </div> 
                 
                 <?= '<div class="panel-body"><h3>'. $model->answer .'</h3></div>';?>
                 
                  </div> 



The relevant parts here are $model->question and $model->answer, which are made available to us because we use findModel to find that instance of the Faq model.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s