Unknown Method and Wrong Redirect after Creating First Form

Unknown Method and Wrong Redirect after Creating First Form

  • 08 Sep 2016
  • 10

In chapter 2 (around pages 54-56) we should now be able to save a record using our new form but you may run into some errors such as being redirected to the wrong page after submission and an unknown method error.

This post is specific to the 'Web Application Development with Yii 2 and PHP' book

We first created the CustomerController.php file on pages 39/40 after putting the tests together. In that file in the actionIndex function we have the following line:

$records = $this->getRecordsAccordingToQuery();

If you are seeing an error saying:

Calling unknown method: app\controllers\CustomersController::getRecordsAccordingToQuery()

That's because the name of the function changes on page 55 when we need to use it. This is probably obvious as the function is explained on this page, but, if like me you left the actionIndex as it was assuming the function name was the same, you will need to go back and change it to:

$records = $this->findRecordsByQuery();

Also, after adding the new functions that use ArrayDataProvider and Yii::$app you need to update the classes at the top of the file to be able to access them:

namespace app\controllers;
use \yii\web\Controller;
use app\models\customer\Customer;
use app\models\customer\CustomerRecord;
use app\models\customer\Phone;
use app\models\customer\PhoneRecord;
use yii\data\ArrayDataProvider;
use Yii;

After the form saves and you get redirected to the index page you may find that the redirect takes you to the root of your localhost. I fixed this by changing the redirect to:

return $this->redirect('customers');

After the redirect works you will get a screen showing no results. If you carry on reading the book without getting too bogged down in why then it explains that this should happen. I tried to fix it before carrying on and found that the redirect method has changed from $this->redirect recently, so I ended up adding the phone_number in an array with the redirect using the following line in the controller:

return Yii::$app->getResponse()->redirect(array('customers', 'phone_number'=>$phone->number));