Yii 2 FAQ

Already on page 3 and no code yet. Don’t worry, it’s coming. In fact, let’s jump in now with some code. In addition to our search method on our FaqSearch model, we are going to add a method named defaultProvider. The purpose of this method is to provide the data for a list of FAQs sorted by faq_value. This will allow the end user to control where the question appears on the list, simply by adjusting the value up or down.

So go ahead and add this method:


public function defaultProvider(){
        
        $query = new Query;
        $provider = new ArrayDataProvider([
            'allModels' => $query->from('faq')->all(),
            'sort' => [
            'defaultOrder' => [
                'faq_value' => SORT_ASC, 
            
            ],
            'attributes' => ['question', 'answer', 'faq_value'],
            ],
            'pagination' => [
            'pageSize' => 10,
            ],
            ]); 

            return $provider;
     
    }

Ok, let’s step through it. We start by creating an instance of Query, which will alllow us to create a query within the instance of ArrayDataProvider. Please note that we need to pull in the following for this to work:


use yii\data\ArrayDataProvider;
use yii\db\ActiveQuery;
use yii\db\Query;

So make sure the use statements are in the appropriate place at the top of the file. Yii 2 does an excellent job of complaining, so if you do leave one out, it will let you know what’s missing.

Ok, back to the code. I referenced the guide for this example, so if you check the guide you will see it is exactly in that format.

The ArrayDataProvider is configured with the type of array config pairs we see in many places on Yii 2. In this case, we have an ‘allModels’ key, which points to a query as value, which returns all the faq record results. And since we are using ArrrayDataProvider, we know we will be returning an array.

The guide doesn’t show you how to set a default order, but I figured that out. We set the default order to faq_value, SORT_ASC, which means it will sort in ascending value. This means an FAQ with a value of 1 will come 1st on the list.

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