Symfony 1.2 Admin with custom primary key

April 27, 2009 – 10:40 pm

Playing with the Symfony 1.2 Admin Generator I noticed that “out-of-the-box” it only likes to play with integer primary keys (ideally based on auto-increment columns I assume). Now, there are cases where you want to use primary keys that aren’t neccessarily numeric, for example countries or languages, where you could use the corresponding ISO codes as id.

When trying this with the new admin generator, all looks fine initially (”list” action works, “new” action works), but when you try to edit a record, which happens automatically after creating one, you will get a “404 Page not found” error. Looking at the logs you’ll see that Symfony interprets the non-numeric id as action name, and matches it with the :module/:action route. Of course this action doesn’t exist, resulting in above-mentioned error.

What’s going on here? Turns out, the culprit is the object routing class that the admin generator uses for generated modules. In my case the responsible class is called “sfPropelRouteCollection”, and it seems to expect the id column to be numeric, judging by it’s default setting for the requirements:

d+

In above expression the d is regulatory speak for “a numeric character”, and the + means “one or more”. Luckily for us, all it takes is changing this requirement setting to make the generated modules work with non-numeric primary keys as well! The pattern that worked best for me is this:

[dw]+

Translated this means “either a numeric character or a letter character”, and “one or more” of those. Depending if you have special characters in your primary key (you really shouldn’t), you may have to massage this pattern a little, but take care to watch for “/” and “.” since those are used by Symfony’s routing to tokenize the url request.

The place to put this updated requirements is the routing.yml file, where it would look somewhat like this:

customer:
  class: sfPropelRouteCollection
  options:
    model:               Countries
    module:             countries
    prefix_path:    countries
    column:              id
    with_wildcard_routes: true
  requirements:  { id: "[dw]+" }

Watch out that the requirements entry is on the same level as class and options.

Needless to say I was very relieved when I found that this is less of a bug than a conventions issue, and that the admin generator didn’t completely break down on such a trivial requirement.

Happy custom Pk’ing!


Filed under: Symfony — Tags: — by Richtermeister

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress