Wednesday, February 25, 2015

cakephp controller save from scaffolded "join table" relationship, non-conventional primary keys

When I build interfaces on top of a pre-established database schema, I usually can't change schema properties.  That's a problem when working with a "convention over configuration" MVC Framework like cakephp.

After baking/scaffolding a CRUD interface based on a "join table" (HABTM) class, that issue came into focus, once again.  I have had run into some fairly easily resolvable issues involving some non conventional naming in the schema, such as primary key names.  I had primary key names from different tables that included the table prefix as well as irregular pluralization in the names.  Initially I wasn't able to get my dropdowns to populate from related tables, as described in the previous post.  Then I ran into an even stickier problem: the save method would fail on validation in the add method of the join table controller.

As it turned out, the form helper input method, though it would accept various names (probably cake-conventional) to refer to itself and to the primary key field, would not accept the ACTUAL name of the primary key field (which, while cake-unconventional, was actually set in both its own class model using $primaryKey and the join model using $foreignKey -- BTW, the same name was in use in the join table database, so this was really convention over configuration coming back to bite me).

To fix this I added the following to the controller to remap the cake-conventional failing field names to the actual (working!) field names:




I discovered, subsequently, that defining foreignKey (of parent) in child class models fixes some issues ... may even fix issue that I describe above.

Relates to: Cakephp SQL Error 1054 Unknown Column In The Field List (id column)

No comments: