0

How could i change the label of a form field after a submit of them?

Example form

class TestType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('test', 'number')
            ->add($options['data']->getId() > 0 ? 'save' : 'add', 'submit')
        ;
    }

    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        if($form->has('add'))
        {
            $form->remove('add');
            $form->add('add', 'submit', array('label' => 'save'));
        }
    }

    public function getName()
    {
        return '';
    }
}

The form is completely generated with "{{ form(form) }}". I only use the FormType. There is a add button if the data['id'] is lower as 1. if the id is higher as 0 there is a save button.

After the first submit of a new form, the entity is saved and after finished page load i see the "add" field instead the "save" field.

If i reload the complete page manually, i see the save button...

Patrick
  • 829
  • 2
  • 13
  • 34

1 Answers1

2

You don't need the finishView method to achieve what you want. You're removing and re-adding the add button in there. This does not make any sense.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $buttonName = $options['data']->getId() > 0 ? 'save' : 'add';
    $builder
        ->add( /* ... */)
        ->add($buttonName, 'submit', array('label' => $buttonName))
    ;
}
Nicolai Fröhlich
  • 51,330
  • 11
  • 126
  • 130