2011-10-27 07:56
浏览 193


Is there an easy way to set a default value for text form field?

图片转代码服务由CSDN问答提供 功能建议


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

23条回答 默认 最新

  • douhuai2015 2011-10-27 10:07

    Can be use during the creation easily with :

    ->add('myfield', 'text', array(
         'label' => 'Field',
         'empty_data' => 'Default value'
    打赏 评论
  • doucheng7234 2011-10-27 08:11

    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:

    打赏 评论
  • dongyan1993 2013-03-20 16:19

    If you need to set default value and your form relates to the entity, then you should use following approach:

    // buildForm() method
    public function buildForm(FormBuilderInterface $builder, array $options) {
                'data' => isset($options['data']) ? $options['data']->getMyField() : 'my default value'

    Otherwise, myField always will be set to default value, instead of getting value from entity.

    打赏 评论
  • doufuhao0566 2013-04-03 18:30

    If your form is bound to an entity, just set the default value on the entity itself using the construct method:

    public function __construct()
        $this->field = 'default value';
    打赏 评论
  • doudi2229 2013-08-01 06:37

    Default values are set by configuring corresponding entity. Before binding the entity to form set its color field to "#0000FF":

    // controller action
    $project = new Project();
    $form = $this->createForm(new ProjectType(), $project);
    打赏 评论
  • drhqkz3455 2013-08-01 06:38

    Approach 1 (from

    Simply set the default value in your entity, either in the variable declaration or the constructor:

    class Entity {
        private $color = '#0000FF';


    class Entity {
        private $color;
        public function __construct(){
             $this->color = '#0000FF';

    Approach 2 from a comment in the above link, and also Dmitriy's answer (not the accepted one) from How to set default value for form field in Symfony2?

    Add the default value to the data attribute when adding the field with the FormBuilder, adapted from Dmitriy's answer.

    Note that this assumes that the property will and will only have the value null when it's a new, and not an existing, entity.

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('color', 'text', array(
                'label' => 'Color:',
                'data' => (isset($options['data']) && $options['data']->getColor() !== null) ? $options['data']->getColor() : '#0000FF'
    打赏 评论
  • dongzhi8984 2013-08-01 15:27

    Just so I understand the problem.

    You want to adjust the way the form is built based on data in your entity. If the entity is being created then use some default value. If the entity is existing use the database value.

    Personally, I think @MolecularMans's solution is the way to go. I would actually set the default values in the constructor or in the property statement. But you don't seem to like that approach.

    Instead you can follow this:

    You hang a listener on your form type and you can then examine your entity and adjust the builder->add statements accordingly based on havine a new or existing entity. You still need to specify your default values somewhere though you could just code them in your listener. Or pass them into the form type.

    Seems like a lot of work though. Better to just pass the entity to the form with it's default values already set.

    打赏 评论
  • drmg17928 2013-08-07 12:53

    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.

    Constructor In 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's I 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();
       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 entities Create 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 form In 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->setDate( date('Y-m-d');
    $form = $this->createForm(...)

    Form Events When 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 forms Similar 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.

    Twig You 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(, {attr: { value : default } });

    JS It'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 service For 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.

    Conclusion As 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 ;)

    打赏 评论
  • duanboshe0001 2013-09-06 14:51

    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')

    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)
    打赏 评论
  • douwen4178 2013-12-14 20:10

    My solution:

    $defaultvalue = $options['data']->getMyField();
    $builder->add('myField', 'number', array(
                'data' => !empty($defaultvalue) ? $options['data']->getMyField() : 0
            )) ;
    打赏 评论
  • dongmeng4742 2014-01-24 17:37

    you can set the default value with empty_data

    $builder->add('myField', 'number', ['empty_data' => 'Default value'])
    打赏 评论
  • doutou19761022 2014-03-11 10:19

    If that field is bound to an entity (is a property of that entity) you can just set a default value for it.

    An example:

    public function getMyField() {
        if (is_null($this->MyField)) {
            $this->setMyField('my default value');
        return $this->MyField;
    打赏 评论
  • donglu7816 2014-03-14 10:35

    Often, for init default values of form i use fixtures. Of cause this way is not easiest, but very comfortable.


    class LoadSurgeonPlanData implements FixtureInterface
        public function load(ObjectManager $manager)
            $surgeonPlan = new SurgeonPlan();
            $surgeonPlan->setName('Free trial');

    Yet, symfony type field have the option data.


    $builder->add('token', 'hidden', array(
        'data' => 'abcdef',
    打赏 评论
  • dongmieqiao3152 2014-07-07 15:46

    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)
    打赏 评论
  • dourui7186 2014-10-08 13:07

    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.

    打赏 评论
  • dourukeng5302 2015-07-01 07:42

    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');
    打赏 评论
  • duan3601 2016-04-18 16:05
    ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
         $form = $event->getForm(); 
         $data = $event->getData(); 
         if ($data == null) {
             $form->add('position', IntegerType::class, array('data' => 0));
    打赏 评论
  • dongya3627 2016-10-16 15:11

    A general solution for any case/approach, mainly by using a form without a class or when we need access to any services to set the default value:

    // src/Form/Extension/DefaultFormTypeExtension.php
    class DefaultFormTypeExtension extends AbstractTypeExtension
        public function buildForm(FormBuilderInterface $builder, array $options)
            if (null !== $options['default']) {
                    function (FormEvent $event) use ($options) {
                        if (null === $event->getData()) {
        public function configureOptions(OptionsResolver $resolver)
            $resolver->setDefault('default', null);
        public function getExtendedType()
            return FormType::class;

    and register the form extension:

        class: App\Form\Extension\DefaultFormTypeExtension
            - { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FormType }

    After that, we can use default option in any form field:

    $formBuilder->add('user', null, array('default' => $this->getUser()));
    $formBuilder->add('foo', null, array('default' => 'bar'));
    打赏 评论
  • douhuan1979 2017-05-11 13:12

    As Brian asked:

    empty_data appears to only set the field to 1 when it is submitted with no value. What about when you want the form to default to displaying 1 in the input when no value is present?

    you can set the default value with empty_value

    $builder->add('myField', 'number', ['empty_value' => 'Default value'])
    打赏 评论
  • dongyi2993 2017-07-07 08:17

    If you set 'data' in your creation form, this value will be not modified when edit your entity.

    My solution is :

    public function buildForm(FormBuilderInterface $builder, array $options) {
        // In my example, data is an associated array
        $data = $builder->getData();
        $builder->add('myfield', 'text', array(
         'label' => 'Field',
         'data' => array_key_exits('myfield', $data) ? $data['myfield'] : 'Default value',


    打赏 评论
  • douyin4561 2018-03-27 13:46

    Don't use:

    'data' => 'Default value'

    Read here:

    "The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted."

    Use the following:

    Lets say, for this example, you have an Entity Foo, and there is a field "active" (in this example is CheckBoxType, but process is the same to every other type), which you want to be checked by default

    In your FooFormType class add:

    use Symfony\Component\Form\FormEvent;
    use Symfony\Component\Form\FormEvents;
    public function buildForm( FormBuilderInterface $builder, array $options )
        $builder->add('active', CheckboxType::class, array(
            'label' => 'Active',
            function(FormEvent $event){                 
                $foo = $event->getData();
                // Set Active to true (checked) if form is "create new" ($foo->active = null)
                if(is_null($foo->getActive())) $foo->setActive(true);
    public function configureOptions( OptionsResolver $resolver )
            'data_class' => 'AppBundle:Foo',
    打赏 评论
  • duanjinchi1982 2019-05-06 09:09

    I solve this problem like this in symfony 3.4

    public function buildForm(FormBuilderInterface $builder, array $options)
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $e) {
            if (!$e->getData()) {
                // in create new mode
                    ->add('field', NumberType::class, ['data' => 0 /*Default value here*/] );
    打赏 评论
  • dqz86173 2019-08-27 06:22

    I solved this problem, by adding value in attr:

    ->add('projectDeliveringInDays', null, [
        'attr' => [
    打赏 评论

相关推荐 更多相似问题