Symfony 1.4: Add and Update Created_at and Updated_at Fields Automatically

   Posted February 1, 2011 by David Kirk in Symfony

After the CRUD building process with symfony, beginners are often perplexed with the handling of the created_at and updated_at fields on their forms. These fields are typically best handled behind the scenes. Here is how to let symfony take control of these fields automatically.

Symfony is a wonderful framework for getting content developed quickly. However, the downside is sometimes it’s difficult to remember what needs to be built manually and what things need to be edited.

After initially building CRUD, many users get discouraged at something like this:

Nobody really wants to enter created_at and updated_at fields manually. Luckily, symfony will do this for you if you will just get those fields off your form.


class GameForm extends BaseGameForm
public function configure()
unset($this['created_at'], $this['updated_at']);

Next, you will need to remove this from your form rendering code which is likely found in templates/_form.php. In my example, I need to REMOVE the following code from this file:

        <th><?php echo $form['created_at']->renderLabel() ?></th> 
          <?php echo $form['created_at']->renderError() ?> 
          <?php echo $form['created_at'] ?> 
        <th><?php echo $form['updated_at']->renderLabel() ?></th> 
          <?php echo $form['updated_at']->renderError() ?> 
          <?php echo $form['updated_at'] ?> 

Your rendering will obviously change:

However, your those fields which you have removed from your forms will now be correctly updated when you insert or update the object in the datebase.

Obviously, the more you set away from the generic crud, you need for creating and updated these fields will grow more complex. Hopefully, however, this will get beginners started.


About David Kirk

David Kirk is one of the original founders of tech-recipes and is currently serving as editor-in-chief. Not only has he been crafting tutorials for over ten years, but in his other life he also enjoys taking care of critically ill patients as an ICU physician.
View more articles by David Kirk

The Conversation

Follow the reactions below and share your own thoughts.

  • Oscar

    thanks for the trick, but I want to go further. What happens if you want to show the created_at in the form, but having it filled automatically?

    I’d like the not showing the created_field in “new” action, but in “edit” action.

    I’ve tried this:

    title: my tittle
    display: [field1,field2,created_at]
    title: my tittle
    display: [field1,field2]

    The problem is that when I create the record, it throws created_at required field.

    Do you know how could I accomplish this?


  • Dvaid

    Thanks! It helped me.