Class Not Found Errors after Creating First Form
In chapter 2 (p53) we should be able to view our newly created form, but it's likely (if you are just following along with the book) that you will be getting errors such as 'Class 'app\controllers\CustomerRecord' not found' when trying to view the page.
This post is specific to the 'Web Application Development with Yii 2 and PHP' book
When we first created the CustomersController.php file, we added the namespace and told it to use one of yii's classes
namespace app\controllers; use \yii\web\Controller;
After creating our new classes, we need to add them to the file so that they can be used.
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;
After giving the classes to use, you are likely to be hit by another error:
Unable to find 'app\models\customer\PhoneRecord' in file: crmapp/models/customer/PhoneRecord.php. Namespace missing?
There are a couple of reasons for this. The first is that when we created the index.php file in the web folder we didn't add the composer autoloader path to it. The whole file should look like this:
<?php ini_set('display_errors', true); define('YII_DEBUG', true); // Including the Composer autoloader. require(__DIR__ . '/../vendor/autoload.php'); // Including the Yii framework itself (1) require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php'); // Getting the configuration (2) $config = require(__DIR__ . '/../config/web.php'); // Making and launching the application immediately (3) (new yii\web\Application($config))->run();
After including the autoloader, you might also need to tell composer to regenerate the autoload classes
composer dump-autoload --optimize
You will now be hit with another error:
Exception (Invalid Configuration) 'yii\base\InvalidConfigException' with message 'Unknown component ID: db'
This is because we have only added the database configuration to the config/console.php file and not to config/web.php which needs the following line in the components array
'db' => require(__DIR__ . '/db.php'),
Now, as long as you have created the assets folder in the web root you should now see a form! Phew