I often forget how to set default values for form fields. Mainly because it’s a function of sfForm rather than sfFormField I think. In the snippet below ‘field’ you are setting the default value for, and $value should be the default value.
1 2 3 4 5 6 | <?php // lib/form/MyModelForm.class.php public function configure() { $this->setDefault('field', $value); } ?> |
A Note on Snippets: When using frameworks such as Symfony it is often the simplest pieces of code which are the hardest to either find or remember. These snippets are placed here for my own reference and will hopefully be useful to others. If you find them useful or have any suggestions, please let me know.




4th Jun
Joe says:
Thank you – just what I needed
8th Jun
ErisDS says:
You’re very welcome :)
7th Aug
Dratir says:
Another possibility is to set the default value in the schema. However, I think its prefferable to set it in the Form rather than changing the Database every time ;)
30th Oct
Pedro Casado says:
Cool! I like snippets like these ;D
17th Dec
atze says:
it’s been a while, working with symfony – started digging in the widget-codes for default value etc…
found your little snippet – voilá
thx alot, merry chistmas & happy new year
17th May
Ikon says:
Thank you!
I was totally depressed when trying to set the default value through the widgetschema, which should be fine but actually not. But setting the default value through the form is working perfectly.
More snippets like this pls! XD
18th Jun
Apul says:
But, How to pass these default values from action?
18th Jun
ErisDS says:
@Apul You wouldn’t (and can’t as fas as I am aware) pass a “default” value from an action to a form. Either the form itself has a “default” value (and is set as shown in this Snippet) or the object passed to the form has a “default” value.
If you have values to assign to the form from your action, then you would set these on a relevant object, and then pass the object to the form as shown here:
2
3
4
5
6
7
8
9
10
11
12
//apps/myApp/modules/myModule/actions/actions.class.php
public function executeMyAction(sfWebRequest $request)
{
// create an object for the form
$object = new MyObject();
// object already has default values, or to set additional ones:
$object->setValue('Default');
// instantiate the new form with it's object
$this->form = new MyObjectForm($object);
}
?>
I hope this answers your question?
18th Jun
Apul says:
Yes. That’s the thing.
Thanks.
21st Sep
Jorgo says:
Very nice. Thank you.
I wasn’t aware that I could set the values directly on the object.
Here’s an example how I was setting the defaults:
2
3
4
5
6
7
8
'cart_id' => $this->getUser()->getAttribute('cart_id'),
'product_id' => $this->product['product_id'],
'quantity' => 1
);
$this->form = new AddToCartForm();
$this->form->setDefaults(array_merge($this->form->getDefaults(), $myDefaults));
17th Nov
Richard says:
Thank you!
I often forget the simply things. @Jorgo, thanks for posting the array method aswell – that will come in handy :)