Getting Started - Problem with Gii CRUD Creation

I have been working through the getting started guide for Yii, in particular Working with Databases and Code Generation using Gii

I had to modify the CountryController.php file, findModel function which was referencing “id”

if (($model = Country::findOne($id)) !== null) {

when changed to “code” this worked.

 protected function findModel($code)
        if (($model = Country::findOne($code)) !== null) {
            return $model;

        throw new NotFoundHttpException('The requested page does not exist.');

After generating the CRUD code I receive an error when clicking on the “View/Edit/Delete” buttons. It appears that the generated links are incorrect in that they reference “id” rather than “code” (which is the primary key).

E.g the View link is http://localhost/yii/demo/basic/web/index.php?r=country%2Fview&id=AU which generates the error :- Bad Request (#400) Missing required parameters: code when I manually change the link to :- http://localhost/yii/demo/basic/web/index.php?r=country%2Fview&code=AU It works correctly, why is it referencing “id” ?

Does anyone have any ideas, the db is MySQL and the Code column is defined as the Primary Key.


Hi @asheers

Gii seems to be using the name ‘id’ for the variable which holds the value of the primary key, disregarding the actual name of the primary key. I mean, whether it is ‘id’ or ‘code’, gii will use ‘id’ in the CRUD generation.

So, I’m not very sure, but what you can do might be whether

  1. Undo the change of “id” to “code”. Or,
  2. Change every “id” to “code”.

For the first option, I think that $model = Country::findOne($id) will work as expected, because findOne() doesn’t care the name of the parameter and will compare it to the primary key named “code”.

1 Like

Thanks @softark I have changed all the parameter references of $code to $id in the CountryController.php file and it all seems to work ok.

Thanks for your help

Just as a side note, the following wiki article might be helping for you.

It has the following chapter, and this issue of yours looks like an example that demonstrates its validity.

DO name a table’s own ID column “id”

Thanks again @softark , but I was just following the yii getting started guide, which uses a countries example and the table has a column called Code which is a two character code for each country, e.g. FR for France, and this is used as the Table’s Primary key… When I start my own development I will use “id” as the PKs for each table I develop, although I don’t think that it is good DB practice, but that probably depends on which DBA you are talking to :slight_smile:

1 Like

Oh, yeah. You are totally right. It’s not a fault of yours at all.

I didn’t know (or forgot) that the “Working with Database” section of guide uses “code” for the primary key of “country” table, and “Generating Code with Gii” section follows right after it. It’s misleading.

Anyway, have a good day !!

1 Like