Symfony World blog is not maintained anymore. Check new sys.exit() programming blog.

Default form values for new objects

what for?

Sometimes you may need to get some random values when creating a new object from the symfony generated form. This can happen in lots of situations, some of them are listed below:

  • populating article comments in a community website - a community website looks a lot better when each article has at least several comments. So when an article is created, few comments need to be created right afterwards. Choosing random names is quite easy, of course, but what if your system allows only logged in users to leave comments (which means, comment table row does not have author string value, but author_id integer foreign key)? In such case you have to look up a random user id in the database, which is pretty impossible. Default form values to the rescue!
  • E-shop product attributes - each product has some attributes that measure its quality, just like reliability, aesthetics, performance and so on. As we know, many information in advertisement is pure bull*hit nowadays, e.g. values of product attributes are probably fabricated. Suppose there are many attributes for each product (available inside the form or inside an embedded form, it doesn't matter). Defining each attribute costs time and an E-commerce shop employee will work slower if he needs to input each value separately. Again, default form values comes with assistance!


Put the following code into the setup or configure method of a form class:

if ($this->isNew())
  $this->setDefault('name', Tools::getRandomName());

Above feature is really easy to implement and you'll find it really useful when generating some partially random data. Of course, you may also set random values after the form is submitted, when a form field is simply disabled - but then you don't have a posibility to change it during object creation.

No comments:

Post a Comment