Skip to content

Adding non-entity fields to your Symfony2 forms

by rich on July 20th, 2011

I’ve had a case recently whereby I needed to implement a registration form in my current Symfony2 application, based on a Mandango model. This form consisted of selected fields from my model, along with a separate “I accept the terms and conditions” checkbox; pretty standard. In Symfony 1, it was straightforward to add in non-model fields, however in Symfony2 the convention for forms is to create a domain model which represents your form, which then gets populated with the data.

Initially I went with extending from the Mandango model (in my case, Model\MyOwnBundle\User being the original model) and adding in a separate get/setTermsAndConditions() method, but this caused problems when saving the model down, as Mandango couldn’t find the document class (since I’d extended it and called it UserRegistration).

After a bit of digging and experimentation however, the following code does what I need it to, without having to extend my existing model or create a new one (which I’d then have to use to populate my actual Mandango model):

class RegisterFormType extends AbstractType
{
    /**
     * Constructs our registration form
     * 
     * @param \Symfony\Component\Form\FormBuilder $builder
     * @param array $options
     * @return void
     */
    public function buildForm(FormBuilder $builder, array $options)
    {
        // Build the form
        $builder->
            add("firstName", "text")->
            add("lastName", "text")->
            add("emailAddress", "email")->
            add("t_and_c",
                "checkbox",
                array(
                    "property_path" => false,
                )
            );
 
        // "True" validator on the form for t&c
        $builder->
            addValidator(new CallbackValidator(function(FormInterface $form)
            {
                if (!$form["t_and_c"]->getData())
                {
                    $form->addError(new FormError('Please accept the terms and conditions in order to register'));
                }
            })
        );
    }
 
    // ...
}

The above adds the t_and_c field but using "property_path" => false means it’s not validated against the model and therefore no need to implement separate get/set() methods. Instead we use a callback validator on the form to check the value of the t_and_c field and ensure it’s been checked. Et voila :-)

I've had a case recently whereby I needed to implement a registration form in my current Symfony2 application, based on a Mandango model. This form consisted of selected fields from my model, along with a separate "I accept the terms and conditions" checkbox; pretty standard. In Symfony 1, it was straightforward to ...

From → php, symfony

6 Comments
  1. spacer
    Richard Miller permalink

    Thanks for this, this is something I have a need for at the moment, you have made it easy to do now. I thought it was going to take a fair amount of digging about to work it out.

    Reply
    • spacer
      cordoval permalink

      is it really it?

      Reply
  2. spacer
    cordoval permalink

    hmmm

    i tend to think that still there is a problem in the way you are doing things
    what if there are more scenarios for this or more fields etc it could become hard to handle that is why we are trying to solve the same problem

    www.craftitonline.com/2011/07/symfony2-famous-ozmerks-form-model-pattern/

    Please let us know, thanks

    Reply
    • spacer
      rich permalink

      If you start adding more and more fields, then you should be using a specific domain model to handle validation and deal with the data set/gets as appropriate. This example is only intended for eg a user registration form, so using a model in its entirety (or near enough), plus maybe one additional field that doesn’t require storage. Otherwise, if you start adding more and more fields, your code will quickly become a mess ;-)

      Reply

Trackbacks & Pingbacks

  1. Craft It Online! » Adding non-entity fields to your Symfony2 forms: Republish
  2. Craft It Online! » Adding non-entity fields to your Symfony2 forms: Republished
Click here to cancel reply.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.