Stepashka
Stepashka

Reputation: 2698

Symfony form use defaults from data class after submit

I have a problem working with Symfony forms when some fields are not submitted.

I have data class FormData that have some defaults in it public $page = 1. I use that class when creating a form. When I submit a form and that specific field is not in the request the value in data class is reset to null. While I want it to stay in a default state (1) as it was initially in data class.

I have the following data class (simplified version):

class FormData
{
    /**
     * @Assert\Type("int")
     * @var integer
     */
    public $page = 1;
}

I have the form Type:

class FormType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('page', IntegerType::class);
        }
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'empty_data' => new FormData()
            ));
        }
    }

That's how I use form:

    // $request->has('page') is false 
    $form = $this
        ->formFactory
        ->createNamedBuilder('', EntitiesType:class, new FormData())
        ->getForm();
    $form->handleRequest($request);
    $data = $form->getData(); 
    // $data->page is null while I want it to be 1 

Is there any solution that can keep value of $data->page to 1?

PS: I know that if I do ->add('page', IntegerType::class, ['empty_data' => '1']) for the specific field configuration then the value will be set to 1 but I want it to take the value from the data class.

Upvotes: 0

Views: 859

Answers (1)

Kamil Adryjanek
Kamil Adryjanek

Reputation: 3338

This is because by default for POST requests handleRequest method submits the form with $clearMissing parameter set to true (setting not send parameters to null: https://github.com/symfony/form/blob/master/Form.php#L562). I you want to keep your default values, please use:

$form->submit($data, false);

Upvotes: 2

Related Questions