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).
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
Undo the change of “id” to “code”. Or,
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”.
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
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.