Is there an easy way to set a default value for text form field?
I usually just set the default value for specific field in my entity:
/**
* @var int
* @ORM\Column(type="integer", nullable=true)
*/
protected $development_time = 0;
This will work for new records or if just updating existing ones.
There is a very simple way, you can set defaults as here :
$defaults = array('sortby' => $sortby,'category' => $category,'page' => 1);
$form = $this->formfactory->createBuilder('form', $defaults)
->add('sortby','choice')
->add('category','choice')
->add('page','hidden')
->getForm();
You can set the default for related field in your model class (in mapping definition or set the value yourself).
Furthermore, FormBuilder gives you a chance to set initial values with setData() method. Form builder is passed to the createForm() method of your form class.
Also, check this link: http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class
If you're using a FormBuilder
in symfony 2.7 to generate the form, you can also pass the initial data to the createFormBuilder
method of the Controler
$values = array(
'name' => "Bob"
);
$formBuilder = $this->createFormBuilder($values);
$formBuilder->add('name', 'text');
Can be use during the creation easily with :
->add('myfield', 'text', array(
'label' => 'Field',
'empty_data' => 'Default value'
))
You can set a default value, e.g. for the form message
, like this:
$defaultData = array('message' => 'Type your message here');
$form = $this->createFormBuilder($defaultData)
->add('name', 'text')
->add('email', 'email')
->add('message', 'textarea')
->add('send', 'submit')
->getForm();
In case your form is mapped to an Entity, you can go like this (e.g. default username):
$user = new User();
$user->setUsername('John Doe');
$form = $this->createFormBuilder($user)
->add('username')
->getForm();