Search code examples
formssymfonydto

How to add fields that not defined in Entity?


I want to add same additional fields to my form, but I don't want have ones in data object. Here is an example:

    $formBuilder = $this->get('form.factory')->createBuilder(new LeadType(), new LeadInfo());

    $formBuilder->add('newsSubscribe', 'checkbox');
    $form = $formBuilder->getForm();

But I get an error, because there is no 'newsSubscribe' field on my object, and I don't want add(because subscription has no relation to LeadInfo)

Is there a way to solve that?


Solution

  • The field type (which most form fields inherit by default) provides a property_path option that denotes which property on the domain object the field represents. You can tell your checkbox not to write to the domain object like so:

    $formBuilder->add('newsSubscribe', 'checkbox', array(
        'property_path' => false,
    ));
    

    You may have to define other options for your checkbox as well, since you're passing an array that may overwrite default options, but that will get you started. With this code, newsSubscribe will be available in your POST variables, but Symfony won't attempt to write it to a domain object property.