How to set default value for form field in Symfony2? How to set default value for form field in Symfony2? symfony symfony

How to set default value for form field in Symfony2?


you can set the default value with empty_data

$builder->add('myField', 'number', ['empty_data' => 'Default value'])


Can be use during the creation easily with :

->add('myfield', 'text', array(     'label' => 'Field',     'empty_data' => 'Default value'))


I've contemplated this a few times in the past so thought I'd jot down the different ideas I've had / used. Something might be of use, but none are "perfect" Symfony2 solutions.

ConstructorIn the Entity you can do $this->setBar('default value'); but this is called every time you load the entity (db or not) and is a bit messy. It does however work for every field type as you can create dates or whatever else you need.

If statements within get'sI wouldn't, but you could.

return ( ! $this->hasFoo() ) ? 'default' : $this->foo;

Factory / instance. Call a static function / secondary class which provides you a default Entity pre-populated with data. E.g.

function getFactory() {    $obj = new static();    $obj->setBar('foo');    $obj->setFoo('bar');   return $obj;}

Not really ideal given you'll have to maintain this function if you add extra fields, but it does mean you're separating the data setters / default and that which is generated from the db. Similarly you can have multiple getFactories should you want different defaulted data.

Extended / Reflection entitiesCreate a extending Entity (e.g. FooCreate extends Foo) which gives you the defaulted data at create time (through the constructor). Similar to the Factory / instance idea just a different approach - I prefer static methods personally.

Set Data before build formIn the constructors / service, you know if you have a new entity or if it was populated from the db. It's plausible therefore to call set data on the different fields when you grab a new entity. E.g.

if( ! $entity->isFromDB() ) {     $entity->setBar('default');     $entity->setDate( date('Y-m-d');     ...}$form = $this->createForm(...)

Form EventsWhen you create the form you set default data when creating the fields. You override this use PreSetData event listener. The problem with this is that you're duplicating the form workload / duplicating code and making it harder to maintain / understand.

Extended formsSimilar to Form events, but you call the different type depending on if it's a db / new entity. By this I mean you have FooType which defines your edit form, BarType extends FooType this and sets all the data to the fields. In your controller you then simply choose which form type to instigate. This sucks if you have a custom theme though and like events, creates too much maintenance for my liking.

TwigYou can create your own theme and default the data using the value option too when you do it on a per-field basis. There is nothing stopping you wrapping this into a form theme either should you wish to keep your templates clean and the form reusable. e.g.

form_widget(form.foo, {attr: { value : default } });

JSIt'd be trivial to populate the form with a JS function if the fields are empty. You could do something with placeholders for example. This is a bad, bad idea though.

Forms as a serviceFor one of the big form based projects I did, I created a service which generated all the forms, did all the processing etc. This was because the forms were to be used across multiple controllers in multiple environments and whilst the forms were generated / handled in the same way, they were displayed / interacted with differently (e.g. error handling, redirections etc). The beauty of this approach was that you can default data, do everything you need, handle errors generically etc and it's all encapsulated in one place.

ConclusionAs I see it, you'll run into the same issue time and time again - where is the defaulted data to live?

  • If you store it at db/doctrine level what happens if you don't want to store the default every time?
  • If you store it at Entity level what happens if you want to re-use that entity elsewhere without any data in it?
  • If you store it at Entity Level and add a new field, do you want the previous versions to have that default value upon editing? Same goes for the default in the DB...
  • If you store it at the form level, is that obvious when you come to maintain the code later?
  • If it's in the constructor what happens if you use the form in multiple places?
  • If you push it to JS level then you've gone too far - the data shouldn't be in the view never mind JS (and we're ignoring compatibility, rendering errors etc)
  • The service is great if like me you're using it in multiple places, but it's overkill for a simple add / edit form on one site...

To that end, I've approached the problem differently each time. For example, a signup form "newsletter" option is easily (and logically) set in the constructor just before creating the form. When I was building forms collections which were linked together (e.g. which radio buttons in different form types linked together) then I've used Event Listeners. When I've built a more complicated entity (e.g. one which required children or lots of defaulted data) I've used a function (e.g. 'getFactory') to create it element as I need it.

I don't think there is one "right" approach as every time I've had this requirement it's been slightly different.

Good luck! I hope I've given you some food for thought at any rate and didn't ramble too much ;)