Jan28

Tagged in:Comments:

Change input name of the form fields in Symfony3

Remove form type name from the form

Sometimes we need to integrate third party application or form, which requires us to remove any array type form names. 

Problem

Normal form will create FormTypeName[fieldName]

<input type="text" value="" name="formTypeName[fieldName]">

Our final outcome should look like field name only without any form type name.

<input type="text" value="" name="fieldName">

Solution 

Create the form using createNamed method.

$form = $this->get('form.factory')->createNamed(null, new MyFormType(), $dataObject, $formOptions);

When you pass first argument as null, it will remove form type name and make fields as field name only.

Solution 2

You can also change your formType and return blockPrefix null.

class MyFormType extends AbstractType
{
    ...

    /**
     * This will remove formTypeName from the form
     * @return null
     */
    public function getBlockPrefix() {
        return null;
    }
}

I recommend first solution.

Post a Comment

You must be logged in to post a comment.

Back to top