简体   繁体   中英

Symfony2 single form to add multiple entries to database at once

I have an Entity

class User
{
  /**
    * @ORM\Column(type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
  protected $id;

  /**
    * @ORM\Column(type="string", length=17)
    */
    protected $mac;

  /**
    * @ORM\Column(type="string", length=10)
    */
    protected $sensor;

  /**
    * @ORM\Column(type="integer", length=4)
    */
    protected $sensitivity;

/** getters and setters **/
}

in the database every user should have three entries because of three different sensors and I need to create a form to add new user with those sensor names ($sensor) and their sensitivities. Is it possible to do this with a single form? Inputs of the form should be to enter mac (text), sensor1 (number), sensor2 (number), sensor2 (number). Is it possible to do this with a single form? How?

Ok so what I've done is created the form with all needed inputs using the createFormBuilder() without providing an Entity. Then I created a new object $user = new User(); and then:

  $em = $this->getDoctrine()->getManager();        
  $user->setMac($form['mac']->getData());
  $user->setSensor('wiliboxas1');
  $user->setSensitivity($form['sensor1']->getData());
  $em->persist($user);
  $em->flush();
  $em->clear();
  $user->setSensor('sensor2');
  $vartotojas->setSensitivity($form['sensor2']->getData());
  $em->persist($user);
  $em->flush();
  $em->clear();

  //and so on..

$em->clear() is also needed because otherwise it will add only a single entry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM