php - Symfony2 one form for many entities Many To One relation -
i need form issue. have main entity - user:
class user { private $id; private $name; private $surname; private $description; private $photo; /** * @orm\onetomany(targetentity="adress", mappedby="user", cascade={"persist", "remove"}) */ private $adresses; /** * @orm\manytomany(targetentity="groups", inversedby="users") * @orm\jointable(name="users_groups") */ private $groups;
i have get, set, __construct etc...
then address entity:
class adress { private $id; private $city; private $street; private $number; /** * @orm\manytoone(targetentity="user", inversedby="adresses", cascade={"persist", "remove"}) * @orm\joincolumn(name="user_id", referencedcolumnname="id") */ private $user;
and form adress:
class adresstype extends abstracttype { public function buildform(formbuilderinterface $builder, array $options) { $builder ->add('city') ->add('street') ->add('number') ->add('user') ; }
etc.. (generate crud)
and form user:
public function buildform(formbuilderinterface $builder, array $options) { $builder ->add('name') ->add('surname') ->add('description') ->add('photo', 'file', array('label' => 'photo (files: .jpg, .png)', 'data_class' => null)) ->add('groups') ->add('adresses', 'collection', array( 'type' => new adresstype(), 'allow_add' => true, 'allow_delete' => true, 'cascade_validation' => true, 'by_reference' => false, ))
controller new user:
private function createcreateform(user $entity) { $adress = new adress(); $entity->addadress($adress); $form = $this->createform(new usertype(), $entity, array( 'action' => $this->generateurl('user_create'), 'method' => 'post', )); $form->add('submit', 'submit', array('label' => 'create')); return $form; } public function createaction(request $request) { $entity = new user(); $form = $this->createcreateform($entity); $form->handlerequest($request); if ($form->isvalid()) { //add photo /** * @var symfony\component\httpfoundation\file\uploadedfile $file */ $photo = $entity->getphoto(); //generate name photo $photoname = md5(uniqid()) . '.' . $photo->guessextension(); $photo->move($this->getparameter('photo_directory'), $photoname); $entity->setphoto($photoname); $em = $this->getdoctrine()->getmanager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateurl('user_show', array('id' => $entity->getid()))); } return array( 'entity' => $entity, 'form' => $form->createview(), ); }
the results this: click here don't know how solve th problem add information 2 entities (user, adress) in 1 form. don't know should 'user' in adresstype - because shows select field want add new relation between adress , user.
can me - spend few hours , can't figure out. :) thank you!
Comments
Post a Comment