How to set default value for form field in Symfony2?

后端 未结 22 1326
暖寄归人
暖寄归人 2020-11-27 13:23

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

相关标签:
22条回答
  • 2020-11-27 13:44

    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.

    0 讨论(0)
  • 2020-11-27 13:49

    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();
    
    0 讨论(0)
  • 2020-11-27 13:51

    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

    0 讨论(0)
  • 2020-11-27 13:51

    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');
    
    0 讨论(0)
  • 2020-11-27 13:54

    Can be use during the creation easily with :

    ->add('myfield', 'text', array(
         'label' => 'Field',
         'empty_data' => 'Default value'
    ))
    
    0 讨论(0)
  • 2020-11-27 13:55

    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();
    
    0 讨论(0)
提交回复
热议问题