Symfony 3 forms: how to set default value for a textarea widget
Asked Answered
G

3

5

I want to set the value on a textarea widget. How i can set default value for textarea in Symfony 3 for TextType(input type="text") i can use value parameter but for textarea i can not!!!how i can set default value for textarea.

this is my buildForm

    public function buildForm(FormBuilderInterface $builder, array $options)
    { 
        $builder
        ->add('linkdin', TextType::class, array('attr' => array('placeholder' => 
'linkdin','class' => 'form-control width100','value' => 
MainPageType::$content1[0]['linkdin'])))

        ->add('addres', CKEditorType::class, array('attr' => array('required' =>
 'false','name'=>'editor1' ,'id' => 'editor1','class' => 'ckeditor','empty_data'
 => MainPageType::$content1[0]['addres'])))
        .
    .
Godfather answered 20/1, 2018 at 13:20 Comment(0)
G
11

Assuming you are using Symfony 3.4, there's quite a good documentation for that.

Long story short, you should use data:

$builder->add('token', TextareaType::class, array(
    'data' => 'abcdef',
));

As the docs say:

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.

Geophyte answered 20/1, 2018 at 13:26 Comment(0)
H
2

You can transfer the variable with data to the formType in controller like that

$form = $this->createForm(Form::class,$YourData);
Handiwork answered 20/1, 2018 at 13:28 Comment(1)
In $YourData you should transfer the object you are willing to display in the form. Editing the object value before you transfer it into the form is considered bad programming.Geophyte
G
1

If you’re using the form for both saving a new record and editing an existing one, chances are that you’ve found the ‘data’ option (Alex’s solution) to be limited, because the fields are overridden with the default data while editing an existing record.

One of the solutions is to set the default data manually in the new() action in your controller, but only on the GET call, not POST.

$form = $this->createForm(MyType::class, $dto);
$form->handleRequest($request);

if($form->isSubmitted()) {
    if($form->isValid()) {
        // Save data
    }
} else {
    // Set default value
    $form->get('date')->setData(
        new\DateTime(’now’)
    );
}
Gomphosis answered 21/8, 2018 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.