Fabian
Fabian

Reputation: 1836

Symfony2: Create form binded to an entity with a field which is not a property

The following (simple) question from me:

  $user = new User();
  $user->setEventid(2);
  $user->setT(new \DateTime('now'));

  $em = $this->getDoctrine()->getManager();
  $em->persist($user);
  $em->flush();

  $form = $this->createFormBuilder($user)
    ->add('email', 'email')
    ->add('terms', 'checkbox', array(
          'label'     => 'Read terms?',
          'required'  => true))
    ->getForm();

This is my code. Email is property of the user, terms not. I want them users to save their email and check the terms-checkbox but i just need to save the email, not if they check the box - if they don't they cant submit the form.

You know what i mean? I'm shure its pretty simple to achieve this ;)

Second Question: How can i give the rendered from-tag an id-attribute for further handeling in jquery?

Upvotes: 1

Views: 859

Answers (2)

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

To add a field that doesn't exist in the entity to a form, use this:

->add('terms', 'checkbox', array(
    'label'         => 'Read terms?',
    'required'      => true,
    'mapped'        => false, // this works since Symfony 2.1
    'property_path' => false, // this works since Symfony 2.0
))

Symfony generates an ID for each form element; just open the rendered page source and see the ID of the element you need.

Upvotes: 2

Jeffrey Muller
Jeffrey Muller

Reputation: 850

If you don't have a 'terms' field in your Entity, it won't be save. For your second question, it's very simple to set an id to a form in twig, make simply :

{{ form_label(form.name, 'Your Name', { 'attr': {'id': 'foo'} }) }}

Upvotes: 0

Related Questions