Custom default values in Symfony 1.4

Hey everyone, it’s been a while.

Lately I’ve started to dig into the php web framework Symfony. I have to say I’m very impressed. It makes building web applications fun again. Adding new features and expanding on current features become very easy.

For my day job as a system admin I’ve been deploying Symfony applications for years, but haven’t been involved with them more than. I’m very glad I finally made the plunge into Symfony myself. After a couple days of banging my head against the wall, slowly climbing the learning curve, things finally started falling in place. And since then I feel my time coding is much more efficient.

Anyways, I had some issues finding solutions to some simple problems, one of them being setting up default values.

In your config/doctrine/schema.yml file you can set models to be timestampable:

actAs: { Timestampable: ~ }

This is a nice and simply way to maintain a created_at and updated_at field. I quickly found out though, that updated_at isn’t just when you edit the file in the backend, but anytime something changes. Which makes sense, but wasn’t what I first assumed.

One of my websites tracks a lot of activity, and the updated_at was a bit heavier than I was looking for. Extra queries can quickly build up and start slowing down your website. I ended up removing the Timestampable option, and instead used a column:

added: { type: date }

Now in order to automatically update the added field only when the entry is created, edit or create the following file using your model name:

class Category extends BaseCategory
public function assignDefaultValues($overwrite = false)
$this->added = date('Y-m-d');

What this does is set the value of added to the current date in the 2011-04-12 format.

In the assignDefaultValues you can set any defaults you like, in the same format as the date is set.

This is very simple to setup when you know how to, but finding out how to set these defaults isn’t as easy as it could be.

I hope this simple post helps some people figure this simple solution out quicker than it took me.

Be Sociable, Share!

Comments are closed.