Symfony2 - Able to add data of multiple entities to database but no foreign keys are added - forms

I got 2 tables connected with a foreign key (user_id is in the table persons). I'm able to add data to both of the tables by executing 1 form.
but on the execute i expected that the foreign key would automatically be generated in the table persons.
Here are my enities
USERS
namespace Geo\CityTroopersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Geo\CityTroopersBundle\Entity\Users
*
* #ORM\Table(name="users")
* #ORM\Entity
*/
class Users
{
//Vanaf hier bijgevoegd
protected $adress;
protected $person;
//Einde zelf toegevoegde properties
/**
* #var integer $userId
*
* #ORM\Column(name="user_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $userId;
/**
* #var string $user
*
* #ORM\Column(name="user_password", type="string", length=128, nullable=true)
*/
private $userPassword;
/**
* #var string $userEmail
*
* #ORM\Column(name="user_email", type="string", length=128, nullable=true)
*/
private $userEmail;
/**
* #var string $userImage
*
* #ORM\Column(name="user_image", type="string", length=128, nullable=true)
*/
private $userImage;
/**
* #var string $userQuestion
*
* #ORM\Column(name="user_question", type="string", length=128, nullable=true)
*/
private $userQuestion;
/**
* #var string $userAnswer
*
* #ORM\Column(name="user_answer", type="string", length=128, nullable=true)
*/
private $userAnswer;
/**
* #var \DateTime $userCreateddate
*
* #ORM\Column(name="user_createddate", type="datetime", nullable=true)
*/
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->userId;
}
/**
* Set userPassword
*
* #param string $userPassword
* #return Users
*/
public function setUserPassword($userPassword)
{
$this->userPassword = $userPassword;
return $this;
}
/**
* Get userPassword
*
* #return string
*/
public function getUserPassword()
{
return $this->userPassword;
}
/**
* Set userEmail
*
* #param string $userEmail
* #return Users
*/
public function setUserEmail($userEmail)
{
$this->userEmail = $userEmail;
return $this;
}
/**
* Get userEmail
*
* #return string
*/
public function getUserEmail()
{
return $this->userEmail;
}
/**
* Set userImage
*
* #param string $userImage
* #return Users
*/
public function setUserImage($userImage)
{
$this->userImage = $userImage;
return $this;
}
/**
* Get userImage
*
* #return string
*/
public function getUserImage()
{
return $this->userImage;
}
/**
* Set userQuestion
*
* #param string $userQuestion
* #return Users
*/
public function setUserQuestion($userQuestion)
{
$this->userQuestion = $userQuestion;
return $this;
}
/**
* Get userQuestion
*
* #return string
*/
public function getUserQuestion()
{
return $this->userQuestion;
}
/**
* Set userAnswer
*
* #param string $userAnswer
* #return Users
*/
public function setUserAnswer($userAnswer)
{
$this->userAnswer = $userAnswer;
return $this;
}
/**
* Get userAnswer
*
* #return string
*/
public function getUserAnswer()
{
return $this->userAnswer;
}
//Zelf toegevoegde getters & setters
public function getPerson()
{
return $this->person;
}
public function setPerson(Persons $person = null)
{
$this->person = $person;
}
public function getAdress()
{
return $this->adress;
}
public function setAdress(Adresses $adress = null)
{
$this->adress = $adress;
}
}
PERSONS
namespace Geo\CityTroopersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Geo\CityTroopersBundle\Entity\Persons
*
* #ORM\Table(name="persons")
* #ORM\Entity
*/
class Persons
{
/**
* #var integer $personId
*
* #ORM\Column(name="person_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $personId;
/**
* #var integer $adressId
*
* #ORM\Column(name="adress_id", type="integer", nullable=false)
*/
private $adressId;
/**
* #var string $personFamilyname
*
* #ORM\Column(name="person_familyname", type="string", length=64, nullable=false)
*/
private $personFamilyname;
/**
* #var string $personFirstname
*
* #ORM\Column(name="person_firstname", type="string", length=64, nullable=false)
*/
private $personFirstname;
/**
* #var boolean $personGender
*
* #ORM\Column(name="person_gender", type="boolean", nullable=false)
*/
private $personGender;
/**
* #var string $personNationality
*
* #ORM\Column(name="person_nationality", type="string", length=45, nullable=false)
*/
private $personNationality;
/**
* #var Users
*
* #ORM\ManyToOne(targetEntity="Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
private $user;
/**
* Get personId
*
* #return integer
*/
public function getPersonId()
{
return $this->personId;
}
/**
* Set adressId
*
* #param integer $adressId
* #return Persons
*/
public function setAdressId($adressId)
{
$this->adressId = $adressId;
return $this;
}
/**
* Get adressId
*
* #return integer
*/
public function getAdressId()
{
return $this->adressId;
}
/**
* Set personFamilyname
*
* #param string $personFamilyname
* #return Persons
*/
public function setPersonFamilyname($personFamilyname)
{
$this->personFamilyname = $personFamilyname;
return $this;
}
/**
* Get personFamilyname
*
* #return string
*/
public function getPersonFamilyname()
{
return $this->personFamilyname;
}
/**
* Set personFirstname
*
* #param string $personFirstname
* #return Persons
*/
public function setPersonFirstname($personFirstname)
{
$this->personFirstname = $personFirstname;
return $this;
}
/**
* Get personFirstname
*
* #return string
*/
public function getPersonFirstname()
{
return $this->personFirstname;
}
/**
* Set personGender
*
* #param boolean $personGender
* #return Persons
*/
public function setPersonGender($personGender)
{
$this->personGender = $personGender;
return $this;
}
/**
* Get personGender
*
* #return boolean
*/
public function getPersonGender()
{
return $this->personGender;
}
/**
* Set personNationality
*
* #param string $personNationality
* #return Persons
*/
public function setPersonNationality($personNationality)
{
$this->personNationality = $personNationality;
return $this;
}
/**
* Get personNationality
*
* #return string
*/
public function getPersonNationality()
{
return $this->personNationality;
}
/**
* Set user
*
* #param Geo\CityTroopersBundle\Entity\Users $user
* #return Persons
*/
public function setUser(\Geo\CityTroopersBundle\Entity\Users $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return Geo\CityTroopersBundle\Entity\Users
*/
public function getUser()
{
return $this->user;
}
}
CONTROLLER
class UserController extends Controller
{
public function registerAction(Request $request)
{
$user = new Users();
$person = new Persons();
//$adress = new Adresses();
$form = $this->createForm(new UserType(), $user);
if ($request->getMethod() == 'POST'){
$form->bindRequest($request);
if($form->isValid()){
$person = $form->getData();
//$adress = $form->getData();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->persist($user->getPerson());
//$em->persist($user->getAdress());
$em->flush();
return $this->redirect($this->generateUrl('indexpage'));
}
}
return $this->render('GeoCityTroopersBundle:User:register.html.twig', array(
'form' => $form->createView(),
));
}
}
USERTYPE
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('person', new PersonType());
$builder->add('userEmail');
$builder->add('userPassword', 'password');
$builder->add('userImage');
$builder->add('userQuestion');
$builder->add('userAnswer');
//$builder->add('adress', new AdressType());
}
public function getName()
{
return 'user';
}
}
PERSONTYPE
class PersonType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('personFamilyname');
$builder->add('personFirstname');
$builder->add('personNationality');
$builder->add('personGender');
//$builder->add('adressId');
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Geo\CityTroopersBundle\Entity\Persons',
);
}
public function getName()
{
return 'person';
}
}
I have tried to add in the annotations of Users the following:
/**
* Bidirectional (INVERSE SIDE)
* #ORM\OneToOne(targetEntity="Persons",cascade={"persist"})
*
*/
But this didn't worked either.
I have a feeling there is something wrong with the setup of my database, the relation between persons and users is one to one.
update: Deleted unnecessary
Thanks in advance

Related

FOSUserBundle - Embed formtype

help me please ! I would like to embed form of the FOSUserBundle form in another form builder of an entity. When I do it there is no validation test in user entity. i m novice in symfony.
exemple :
->add('user', RegistrationType::class)
class FolderType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('user', RegistrationType::class)
->add('firstname', TextType::class)
->add('lastname', TextType::class)
->add('dateBirth', BirthdayType::class)
->add('nationality', CountryType::class,
array(
'preferred_choices' => array(
'France', 'FR')
))
->add('phone', NumberType::class)
->add('save', SubmitType::class);
}
add function in controller :
public function addAction(Request $request, School $schoolId)
{
$em = $this->getDoctrine()->getManager();
$school = $em->getRepository('SchoolBundle:School')->findOneById($schoolId);
$candidat = new candidat();
//School Parameter
$candidat->setSchool($schoolId);
$form = $this->createForm('CandidacyBundle\Form\Onepage\FolderType', $candidat, array('schoolId' => $schoolId));
if($request->isMethod('POST') && $form->handleRequest($request)->isValid())
{
//exit(\Doctrine\Common\Util\Debug::dump($candidat));
$em->persist($candidat);
$em->flush();
$this->get('session')->getFlashBag()->add('notice','Yours new candidacy is added !');
return $this->redirectToRoute('candidacy_home');
}
return $this->render('CandidacyBundle:Folder_B:folder.html.twig', array(
'school' => $school,
'new_folder' => $form->createView()
));
}
REGISTRATION TYPE
namespace UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class RegistrationType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder;
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
}
CANDIDAT ENTITY
namespace CandidacyBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Candidat
*
* #ORM\Table()
* #ORM\Entity
*/
class Candidat
{
//x - x - x - x - x - x - x - x - x - x - x - x - x - x - OBJ
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="UserBundle\Entity\User", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
* #Assert\Valid
*/
private $user;
/**
* #ORM\ManyToOne(targetEntity="SchoolBundle\Entity\School")
* #ORM\JoinColumn(name="id_school", referencedColumnName="id", nullable=true)
*/
private $school;
/**
* #var boolean
*
* #ORM\Column(name="state", type="boolean")
*/
private $state = true;
/**
* #var boolean
*
* #ORM\Column(name="state_blacklist", type="boolean")
*/
private $stateBlacklist = false;
/**
* #var \DateTime
*
* #ORM\Column(name="date_entry", type="datetime")
*/
private $dateEntry;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(min=3)
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $firstname;
/**
* #var string
* #Assert\NotBlank(message="Vous devez indiquer votre nom")
* #Assert\Length(min=3)
* #Assert\Regex(
* pattern="/\d/",
* match=false,
* message="Uniquement des lettres"
* )
* #ORM\Column(name="lastname", type="string", length=255, nullable=true)
*/
private $lastname;
/**
* #var \date
* #ORM\Column(name="date_birth", type="date", nullable=true)
*/
private $dateBirth;
/**
* #var string
*
* #ORM\Column(name="nationality", type="string", length=255, nullable=true)
*/
private $nationality;
/**
* #var integer
*
* #ORM\Column(name="phone", type="integer", nullable=true)
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="adress_street", type="string", length=255, nullable=true)
*/
private $adress_street;
/**
* #var string
*
* #ORM\Column(name="adress_city", type="string", length=255, nullable=true)
*/
private $adress_city;
/**
* #var string
*
* #ORM\Column(name="adress_region", type="string", length=255, nullable=true)
*/
private $adress_region;
/**
* #var string
*
* #ORM\Column(name="adress_country", type="string", length=255, nullable=true)
*/
private $adress_country;
/**
* #var integer
*
* #ORM\Column(name="adress_zip", type="smallint", nullable=true)
*/
private $adress_zip;
/**
* #ORM\ManyToOne(targetEntity="SchoolBundle\Entity\Level", cascade={"persist"})
* #ORM\JoinColumn(name="study_current_level", referencedColumnName="id", nullable=true)
*/
private $studyCurrentLevel;
/**
* #var string
*
* #ORM\Column(name="study_current_graduate_name", type="string", length=50)
*/
private $studyCurrentGraduateName;
/**
* #ORM\ManyToOne(targetEntity="SchoolBundle\Entity\Graduate", cascade={"persist"})
* #ORM\JoinColumn(name="study_current_graduate", referencedColumnName="id", nullable=true )
*/
private $studyCurrentGraduate;
/**
* #ORM\ManyToOne(targetEntity="SchoolBundle\Entity\Graduate")
* #ORM\JoinColumn(name="study_widh_graduate", referencedColumnName="id", nullable=true )
*/
private $studyWishGraduate;
/**
* #ORM\ManyToOne(targetEntity="SchoolBundle\Entity\Sector")
* #ORM\JoinColumn(nullable=true)
*/
private $studyWishSector;
/**
* #ORM\ManyToMany(targetEntity="SchoolBundle\Entity\Speciality")
* #ORM\JoinTable(name="candidat_Speciality")
*/
private $studyWishSpecialities;
/**
* #ORM\ManyToOne(targetEntity="SchoolBundle\Entity\Section")
* #ORM\JoinColumn(nullable=true)
*/
private $studyWishSection;
/**
* #ORM\ManyToMany(targetEntity="SchoolBundle\Entity\Diploma", cascade={"persist"})
* #ORM\JoinTable(name="candidat_diploma")
*/
private $studyWishDiplomas;
/**
* #ORM\ManyToOne(targetEntity="SchoolBundle\Entity\Rhythm", cascade={"persist"})
* #ORM\JoinColumn(name="study_wish_rhythm", referencedColumnName="id", nullable=true)
*/
private $studyWishRhythm;
/**
* #var boolean
*
* #ORM\Column(name="study_wish_place_study", type="boolean", nullable=true)
*/
private $studyWishPlaceStudy;
/**
* #ORM\OneToOne(targetEntity="CandidacyBundle\Entity\Attachment", cascade={"all"})
* #ORM\JoinColumn(name="file_picture", nullable=true)
*/
private $picture;
/**
* #ORM\OneToOne(targetEntity="CandidacyBundle\Entity\Attachment", cascade={"all"})
* #ORM\JoinColumn(name="file_cv", nullable=true)
*/
private $cv;
/**
* #ORM\ManyToMany(targetEntity="CandidacyBundle\Entity\Attachment",cascade={"persist"})
* #ORM\JoinTable(name="candidat_attachment")
*/
private $attachments;
//x - x - x - x - x - x - x - x - x - x - x - x - x - x - CONSTRUCT
public function __construct()
{
$this->dateEntry = new \DateTime();
$this->attachments = new ArrayCollection();
}
//x - x - x - x - x - x - x - x - x - x - x - x - x - x - GET/SET
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set state
*
* #param boolean $state
*
* #return Candidat
*/
public function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Get state
*
* #return boolean
*/
public function getState()
{
return $this->state;
}
/**
* Set stateBlacklist
*
* #param boolean $stateBlacklist
*
* #return Candidat
*/
public function setStateBlacklist($stateBlacklist)
{
$this->stateBlacklist = $stateBlacklist;
return $this;
}
/**
* Get stateBlacklist
*
* #return boolean
*/
public function getStateBlacklist()
{
return $this->stateBlacklist;
}
/**
* Set dateEntry
*
* #param \DateTime $dateEntry
*
* #return Candidat
*/
public function setDateEntry($dateEntry)
{
$this->dateEntry = $dateEntry;
return $this;
}
/**
* Get dateEntry
*
* #return \DateTime
*/
public function getDateEntry()
{
return $this->dateEntry;
}
/**
* Set firstname
*
* #param string $firstname
*
* #return Candidat
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
*
* #return Candidat
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set dateBirth
*
* #param \DateTime $dateBirth
*
* #return Candidat
*/
public function setDateBirth($dateBirth)
{
$this->dateBirth = $dateBirth;
return $this;
}
/**
* Get dateBirth
*
* #return \DateTime
*/
public function getDateBirth()
{
return $this->dateBirth;
}
/**
* Set email
*
* #param string $email
*
* #return Candidat
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set nationality
*
* #param string $nationality
*
* #return Candidat
*/
public function setNationality($nationality)
{
$this->nationality = $nationality;
return $this;
}
/**
* Get nationality
*
* #return string
*/
public function getNationality()
{
return $this->nationality;
}
/**
* Set phone
*
* #param integer $phone
*
* #return Candidat
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return integer
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set adressStreet
*
* #param string $adressStreet
*
* #return Candidat
*/
public function setAdressStreet($adressStreet)
{
$this->adress_street = $adressStreet;
return $this;
}
/**
* Get adressStreet
*
* #return string
*/
public function getAdressStreet()
{
return $this->adress_street;
}
/**
* Set adressCity
*
* #param string $adressCity
*
* #return Candidat
*/
public function setAdressCity($adressCity)
{
$this->adress_city = $adressCity;
return $this;
}
/**
* Get adressCity
*
* #return string
*/
public function getAdressCity()
{
return $this->adress_city;
}
/**
* Set adressRegion
*
* #param string $adressRegion
*
* #return Candidat
*/
public function setAdressRegion($adressRegion)
{
$this->adress_region = $adressRegion;
return $this;
}
/**
* Get adressRegion
*
* #return string
*/
public function getAdressRegion()
{
return $this->adress_region;
}
/**
* Set adressCountry
*
* #param string $adressCountry
*
* #return Candidat
*/
public function setAdressCountry($adressCountry)
{
$this->adress_country = $adressCountry;
return $this;
}
/**
* Get adressCountry
*
* #return string
*/
public function getAdressCountry()
{
return $this->adress_country;
}
/**
* Set adressZip
*
* #param integer $adressZip
*
* #return Candidat
*/
public function setAdressZip($adressZip)
{
$this->adress_zip = $adressZip;
return $this;
}
/**
* Get adressZip
*
* #return integer
*/
public function getAdressZip()
{
return $this->adress_zip;
}
/**
* Set studyCurrentLevel
*
* #param string $studyCurrentLevel
*
* #return Candidat
*/
public function setStudyCurrentLevel($studyCurrentLevel)
{
$this->studyCurrentLevel = $studyCurrentLevel;
return $this;
}
/**
* Get studyCurrentLevel
*
* #return string
*/
public function getStudyCurrentLevel()
{
return $this->studyCurrentLevel;
}
/**
* Set studyCurrentGraduateName
*
* #param string $studyCurrentGraduateName
*
* #return Candidat
*/
public function setStudyCurrentGraduateName($studyCurrentGraduateName)
{
$this->studyCurrentGraduateName = $studyCurrentGraduateName;
return $this;
}
/**
* Get studyCurrentGraduateName
*
* #return string
*/
public function getStudyCurrentGraduateName()
{
return $this->studyCurrentGraduateName;
}
/**
* Set studyCurrentGraduate
*
* #param string $studyCurrentGraduate
*
* #return Candidat
*/
public function setStudyCurrentGraduate($studyCurrentGraduate)
{
$this->studyCurrentGraduate = $studyCurrentGraduate;
return $this;
}
/**
* Get studyCurrentGraduate
*
* #return string
*/
public function getStudyCurrentGraduate()
{
return $this->studyCurrentGraduate;
}
/**
* Set studyWishGraduate
*
* #param string $studyWishGraduate
*
* #return Candidat
*/
public function setStudyWishGraduate($studyWishGraduate)
{
$this->studyWishGraduate = $studyWishGraduate;
return $this;
}
/**
* Get studyWishGraduate
*
* #return string
*/
public function getStudyWishGraduate()
{
return $this->studyWishGraduate;
}
/**
* Set studyWishSector
*
* #param string $studyWishSector
*
* #return Candidat
*/
public function setStudyWishSector($studyWishSector)
{
$this->studyWishSector = $studyWishSector;
return $this;
}
/**
* Get studyWishSector
*
* #return string
*/
public function getStudyWishSector()
{
return $this->studyWishSector;
}
/**
* Set studyWishRhythm
*
* #param string $studyWishRhythm
*
* #return Candidat
*/
public function setStudyWishRhythm($studyWishRhythm)
{
$this->studyWishRhythm = $studyWishRhythm;
return $this;
}
/**
* Get studyWishRhythm
*
* #return string
*/
public function getStudyWishRhythm()
{
return $this->studyWishRhythm;
}
/**
* Set studyWishPlaceStudy
*
* #param string $studyWishPlaceStudy
*
* #return Candidat
*/
public function setStudyWishPlaceStudy($studyWishPlaceStudy)
{
$this->studyWishPlaceStudy = $studyWishPlaceStudy;
return $this;
}
/**
* Get studyWishPlaceStudy
*
* #return string
*/
public function getStudyWishPlaceStudy()
{
return $this->studyWishPlaceStudy;
}
/**
* Set user
*
* #param guid $user
*
* #return \UserBundle\Entity\User $user
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set studyWishSpecialities
*
* #param \SchoolBundle\Entity\Speciality $studyWishSpecialities
*
* #return Candidat
*/
public function setStudyWishSpecialities($studyWishSpecialities)
{
$this->studyWishSpecialities = $studyWishSpecialities;
return $this;
}
/**
* Get studyWishSpecialities
*
* #return \SchoolBundle\Entity\Speciality
*/
public function getStudyWishSpecialities()
{
return $this->studyWishSpecialities;
}
public function setPicture(Attachment $picture = null)
{
$this->picture = $picture;
}
public function getPicture()
{
return $this->picture;
}
public function setCv(Attachment $cv = null)
{
$this->cv = $cv;
}
public function getCv()
{
return $this->cv;
}
/**
* Add attachment
*
* #param \CandidacyBundle\Entity\Attachment $attachment
*
* #return Candidat
*/
public function addAttachment(\CandidacyBundle\Entity\Attachment $attachment)
{
$this->attachments[] = $attachment;
return $this;
}
/**
* Remove attachment
*
* #param \CandidacyBundle\Entity\Attachment $attachment
*/
public function removeAttachment(\CandidacyBundle\Entity\Attachment $attachment)
{
$this->attachments->removeElement($attachment);
}
/**
* Get attachments
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAttachments()
{
return $this->attachments;
}
/**
* Set school
*
* #param \SchoolBundle\Entity\School $school
*
* #return Candidat
*/
public function setSchool(\SchoolBundle\Entity\School $school = null)
{
$this->school = $school;
return $this;
}
/**
* Get school
*
* #return \SchoolBundle\Entity\School
*/
public function getSchool()
{
return $this->school;
}
/**
* Add studyWishSpeciality
*
* #param \SchoolBundle\Entity\Speciality $studyWishSpeciality
*
* #return Candidat
*/
public function addStudyWishSpeciality(\SchoolBundle\Entity\Speciality $studyWishSpeciality)
{
$this->studyWishSpecialities[] = $studyWishSpeciality;
return $this;
}
/**
* Remove studyWishSpeciality
*
* #param \SchoolBundle\Entity\Speciality $studyWishSpeciality
*/
public function removeStudyWishSpeciality(\SchoolBundle\Entity\Speciality $studyWishSpeciality)
{
$this->studyWishSpecialities->removeElement($studyWishSpeciality);
}
/**
* Set studyWishSection
*
* #param \SchoolBundle\Entity\Section $studyWishSection
*
* #return Candidat
*/
public function setStudyWishSection(\SchoolBundle\Entity\Section $studyWishSection = null)
{
$this->studyWishSection = $studyWishSection;
return $this;
}
/**
* Get studyWishSection
*
* #return \SchoolBundle\Entity\Section
*/
public function getStudyWishSection()
{
return $this->studyWishSection;
}
/**
* Add studyWishDiploma
*
* #param \SchoolBundle\Entity\Diploma $studyWishDiploma
*
* #return Candidat
*/
public function addStudyWishDiploma(\SchoolBundle\Entity\Diploma $studyWishDiploma)
{
$this->studyWishDiploma[] = $studyWishDiploma;
return $this;
}
/**
* Remove studyWishDiploma
*
* #param \SchoolBundle\Entity\Diploma $studyWishDiploma
*/
public function removeStudyWishDiploma(\SchoolBundle\Entity\Diploma $studyWishDiploma)
{
$this->studyWishDiploma->removeElement($studyWishDiploma);
}
/**
* Get studyWishDiploma
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getStudyWishDiploma()
{
return $this->studyWishDiploma;
}
/**
* Get studyWishDiplomas
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getStudyWishDiplomas()
{
return $this->studyWishDiplomas;
}
}

How to choose displayed field of a form after 'choices' findall?

I would like to choose an other field to display in my form checkboxes.
My Entity Filter has three attributes id, name and subtitle.
My code displays my name values, how to display subtitle values ?
My FormBuilder (Controller):
$formFilter = $this->createFormBuilder()
->add('_', ChoiceType::class,array(
'choices' => $this->getDoctrine()->getManager()->getRepository('loicFilterBundle:Filter')->findAll(),
'multiple' => true,
'expanded' => true,
'choice_label' => function($value, $key, $index) {
return ($value);
},
))
->add('Appliquer filtres', SubmitType::class)
->getForm();
Filter:
namespace loic\FilterBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Filter
*
* * #ORM\Entity(repositoryClass="loic\FilterBundle\Entity\FilterRepository")
* #ORM\Table(name="filter", uniqueConstraints={#ORM\UniqueConstraint(name="idfilter_UNIQUE", columns={"idfilter"})}, indexes={#ORM\Index(name="fk_filter_filter_category1_idx", columns={"filter_category_idfilter_category"})})
*/
class Filter
{
/**
* #var integer
*
* #ORM\Column(name="idfilter", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idfilter;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=true)
*/
private $name;
/**
* #var \FilterCategory
*
* #ORM\ManyToOne(targetEntity="FilterCategory")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="filter_category_idfilter_category", referencedColumnName="idfilter_category")
* })
*/
private $filterCategoryfilterCategory;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="loic\ContentBundle\Entity\Content", mappedBy="filterfilter")
*/
private $contentcontent;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="loic\UserBundle\Entity\User", mappedBy="filterfilter")
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="subtitle", type="string", length=45, nullable=true)
*/
private $subtitle;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=45, nullable=true)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="status", type="string", length=45, nullable=false)
*/
private $status;
/**
* Constructor
*/
public function __construct()
{
$this->contentcontent = new \Doctrine\Common\Collections\ArrayCollection();
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
$this->status = 1;
}
/**
*
* #return the integer
*/
public function getIdfilter() {
return $this->idfilter;
}
/**
*
* #param
* $idfilter
*/
public function setIdfilter($idfilter) {
$this->idfilter = $idfilter;
return $this;
}
/**
*
* #return the string
*/
public function getName() {
return $this->name;
}
/**
*
* #param
* $name
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
*
* #return the \FilterCategory
*/
public function getFilterCategoryfilterCategory() {
return $this->filterCategoryfilterCategory;
}
/**
*
* #param \FilterCategory $filterCategoryfilterCategory
*/
public function setFilterCategoryfilterCategory($filterCategoryfilterCategory) {
$this->filterCategoryfilterCategory = $filterCategoryfilterCategory;
return $this;
}
/**
*
* #return the \Doctrine\Common\Collections\Collection
*/
public function getContentcontent() {
return $this->contentcontent;
}
/**
*
* #param
* $contentcontent
*/
public function setContentcontent($contentcontent) {
$this->contentcontent = $contentcontent;
return $this;
}
public function __toString(){
return $this->name;
}
/**
*
* #return the \Doctrine\Common\Collections\Collection
*/
public function getUser() {
return $this->user;
}
/**
*
* #param
* $user
*/
public function setUser($user) {
$this->user = $user;
return $this;
}
/**
*
* #return the string
*/
public function getSubtitle() {
return $this->subtitle;
}
/**
*
* #param
* $subtitle
*/
public function setSubtitle($subtitle) {
$this->subtitle = $subtitle;
return $this;
}
/**
*
* #return the string
*/
public function getDescription() {
return $this->description;
}
/**
*
* #param
* $description
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
*
* #return the string
*/
public function getStatus() {
return $this->status;
}
/**
*
* #param
* $status
*/
public function setStatus($status) {
$this->status = $status;
return $this;
}
}
You should switch your from field type to EntityType (extends ChoiceType).
There you can overwrite the way the choice_label property is generated.
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
$builder->add('category', EntityType::class, array(
'class' => 'AppBundle:Category',
'choice_label' => function ($category) {
return $category->getDisplayName();
}
));
Sorce: http://symfony.com/doc/current/reference/forms/types/entity.html
Thank you it works. ;)
Also, we can just write the field name like:
'choice_label' => 'subtitle', .
However I wonder how the field was choosen with my previous code.

I get error when I created one form with 2 entities mapped

I have 2 entities, Topic.php and Post.php I would like to have this:
TopicType.php :
<?php
namespace BISSAP\ForumBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TopicType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text', array(
'label' => 'Titre'))
->add('subForm', new PostType())
->add('save', 'submit', array(
'attr' => array(
'class' => 'btn right-flt')))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'BISSAP\ForumBundle\Entity\Topic'
));
}
/**
* #return string
*/
public function getName()
{
return 'bissap_forumbundle_topic';
}
}
PostType.php :
<?php
namespace BISSAP\ForumBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PostType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('content', 'ckeditor', array(
'label' => 'Votre message',
'config_name' => 'my_custom_config',
'config' => array('language' => 'fr')))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'BISSAP\ForumBundle\Entity\Post'
));
}
/**
* #return string
*/
public function getName()
{
return 'bissap_forumbundle_post';
}
}
Topic.php :
<?php
namespace BISSAP\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/*use BISSAP\BodyConcept\Entity\Forum;
*/
/**
* Topic
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\ForumBundle\Entity\TopicRepository")
*/
class Topic
{
/**
* #ORM\ManyToOne(targetEntity="Forum", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $forum;
/**
* #var ArrayCollection $Posts
*
* #ORM\OneToMany(targetEntity="Post", mappedBy="Topic", cascade={"persist", "remove", "merge"})
*/
private $posts;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #ORM\ManyToOne(targetEntity="BISSAP\UserBundle\Entity\User", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var integer
*
* #ORM\Column(name="view_count", type="integer")
*/
private $viewCount;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $dateCreation;
/**
* #var integer
*
* #ORM\Column(name="reply_count", type="integer")
*/
private $replyCount;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="genre", type="string", length=255)
*/
private $genre;
/**
* #var integer
*
* #ORM\Column(name="last_post", type="integer")
*/
private $lastPost;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Topic
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set user
*
* #param integer $user
* #return Topic
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return integer
*/
public function getUser()
{
return $this->user;
}
/**
* Set viewCount
*
* #param integer $viewCount
* #return Topic
*/
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
return $this;
}
/**
* Get viewCount
*
* #return integer
*/
public function getViewCount()
{
return $this->viewCount;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Topic
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set replyCount
*
* #param integer $replyCount
* #return Topic
*/
public function setReplyCount($replyCount)
{
$this->replyCount = $replyCount;
return $this;
}
/**
* Get replyCount
*
* #return integer
*/
public function getReplyCount()
{
return $this->replyCount;
}
/**
* Set slug
*
* #param string $slug
* #return Topic
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set genre
*
* #param string $genre
* #return Topic
*/
public function setGenre($genre)
{
$this->genre = $genre;
return $this;
}
/**
* Get genre
*
* #return string
*/
public function getGenre()
{
return $this->genre;
}
/**
* Set lastPost
*
* #param integer $lastPost
* #return Topic
*/
public function setLastPost($lastPost)
{
$this->lastPost = $lastPost;
return $this;
}
/**
* Get lastPost
*
* #return integer
*/
public function getLastPost()
{
return $this->lastPost;
}
/**
* Set content
*
* #param string $content
* #return Topic
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set forum
*
* #param Forum $forum
* #return Topic
*/
/*public function setForum(\BISSAP\BodyConceptBundle\Entity\Forum $forum)*/
public function setForum(Forum $forum)
{
$this->forum = $forum;
return $this;
}
/**
* Get forum
*
* #return \BISSAP\BodyConceptBundle\Entity\Forum
*/
public function getForum()
{
return $this->forum;
}
/**
* Constructor
*/
public function __construct()
{
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
$this->dateCreation = new \DateTime();
}
/**
* Add posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
* #return Topic
*/
public function addPost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts[] = $posts;
return $this;
}
/**
* Remove posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
*/
public function removePost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts->removeElement($posts);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
Post.php :
<?php
namespace BISSAP\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Post
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\ForumBundle\Entity\PostRepository")
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="BISSAP\UserBundle\Entity\User", inversedBy="Posts", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $dateCreation;
/**
* #var \DateTime
*
* #ORM\Column(name="date_modif", type="datetime")
*/
private $dateModif;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* #ORM\ManyToOne(targetEntity="Topic", inversedBy="Posts", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $topic;
/**
* Constructor
*/
public function __construct()
{
$this->dateCreation = new \DateTime();
$this->dateModif = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set content
*
* #param string $content
* #return Post
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Post
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set dateModif
*
* #param \DateTime $dateModif
* #return Post
*/
public function setDateModif($dateModif)
{
$this->dateModif = $dateModif;
return $this;
}
/**
* Get dateModif
*
* #return \DateTime
*/
public function getDateModif()
{
return $this->dateModif;
}
/**
* Set slug
*
* #param string $slug
* #return Post
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set Topic
*
* #param Topic $topic
* #return Post
*/
/*public function setTopic(\BISSAP\ForumBundle\Entity\Topic $topic)*/
public function setTopic(Topic $topic)
{
$this->topic = $topic;
return $this;
}
/**
* Get Topic
*
* #return \BISSAP\ForumBundle\Entity\Topic
*/
public function getTopic()
{
return $this->topic;
}
/**
* Set user
*
* #param \BISSAP\ForumBundle\Entity\User $user
* #return Post
*/
public function setUser(\BISSAP\UserBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \BISSAP\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
And this is my part of my controller, here i call and use the form:
public function categoryAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$topic = new \BISSAP\ForumBundle\Entity\Topic();
$form = $this->createForm(new TopicType(), $topic);
$user = $this->getUser();
$forum = $em->getRepository('BISSAPForumBundle:Forum')->find(1);
if ($form->handleRequest($request)->isValid()) {
$topic->setUser($user);
$topic->setForum($forum);
$topic->setViewCount(23);
$topic->setReplyCount(123);
$topic->setLastPost(25);
$topic->setSlug('slug_sluggg');
$topic->setGenre('genre');
$em->persist($topic);
$em->flush();
return $this->render('BISSAPForumBundle:F:topic-forum.html.twig', array('user' => $user, 'topic' => $topic));
}
return $this->render('BISSAPForumBundle:F:category-forum.html.twig', array('listTopics' => $listTopics, 'catId' => $catId, 'form' => $form->createView(), 'user' => $user));
}
I have this error : Neither the property "subForm" nor one of the methods "getSubForm()", "isSubForm()", "hasSubForm()", "__get()" exist and have public access in class "BISSAP\ForumBundle\Entity\Topic".
Sur the way is wrong, cause i think, I need to give "$topic objexct" and "$post object" when i used :
$form = $this->createForm(new TopicType(), $topic);
And I had tried, with add(collection) i get similar error!
Thanks U.
The error you get is because you don't have "subform" attribute in your topic class. That name should correspond to the name of the attribute in your topic class.
So this:
->add('subForm', new PostType())
Should be changed to
$builder->add('posts','collection', array( 'type' => new PostType()))
This would be helpful.

Fill my form with the data that I pick up from a table - Symfony2

My problem is this : I have an entity that contains user data , such as:
age
name
surname
address
phone
...
My goal is to make a form where using a query can bring all this data and fill my form with the data , so that the user can modify it if you ever change the cell for example, or changing the direction of his house.
The company and I have made the entity​​ and the form, and consulting the table will do. My problem is how to fill the form fields with the data that I get from the table.
My entity (DatosEntity):
<?php
namespace Proyecto\LavocBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Datos
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Proyecto\LavocBundle\Entity\DatosRepository")
*/
class Datos
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="empresa", type="string", length=50)
*/
private $empresa;
/**
* #var integer
*
* #ORM\Column(name="cuit", type="integer")
*/
private $cuit;
/**
* #var string
*
* #ORM\Column(name="localidad", type="string", length=50)
*/
private $localidad;
/**
* #var string
*
* #ORM\Column(name="calle", type="string", length=40)
*/
private $calle;
/**
* #var integer
*
* #ORM\Column(name="altura", type="integer")
*/
private $altura;
/**
* #var integer
*
* #ORM\Column(name="areaTel", type="integer")
*/
private $areaTel;
/**
* #var integer
*
* #ORM\Column(name="telefono", type="integer")
*/
private $telefono;
/**
* #var integer
*
* #ORM\Column(name="areaCel", type="integer")
*/
private $areaCel;
/**
* #var integer
*
* #ORM\Column(name="celular", type="integer")
*/
private $celular;
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="datos")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $personales;
/**
* #var string
*
* #ORM\Column(name="email", type="string")
*/
private $email;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set empresa
*
* #param string $empresa
* #return Datos
*/
public function setEmpresa($empresa)
{
$this->empresa = $empresa;
return $this;
}
/**
* Get empresa
*
* #return string
*/
public function getEmpresa()
{
return $this->empresa;
}
/**
* Set cuit
*
* #param integer $cuit
* #return Datos
*/
public function setCuit($cuit)
{
$this->cuit = $cuit;
return $this;
}
/**
* Get cuit
*
* #return integer
*/
public function getCuit()
{
return $this->cuit;
}
/**
* Set localidad
*
* #param string $localidad
* #return Datos
*/
public function setLocalidad($localidad)
{
$this->localidad = $localidad;
return $this;
}
/**
* Get localidad
*
* #return string
*/
public function getLocalidad()
{
return $this->localidad;
}
/**
* Set calle
*
* #param string $calle
* #return Datos
*/
public function setCalle($calle)
{
$this->calle = $calle;
return $this;
}
/**
* Get calle
*
* #return string
*/
public function getCalle()
{
return $this->calle;
}
/**
* Set altura
*
* #param integer $altura
* #return Datos
*/
public function setAltura($altura)
{
$this->altura = $altura;
return $this;
}
/**
* Get altura
*
* #return integer
*/
public function getAltura()
{
return $this->altura;
}
/**
* Set telefono
*
* #param integer $telefono
* #return Datos
*/
public function setTelefono($telefono)
{
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* #return integer
*/
public function getTelefono()
{
return $this->telefono;
}
/**
* Set area
*
* #param integer $area
* #return Datos
*/
public function setAreaTel($areaTel)
{
$this->areaTel = $areaTel;
return $this;
}
/**
* Get area
*
* #return integer
*/
public function getAreaTel()
{
return $this->areaTel;
}
/**
* Set celular
*
* #param integer $celular
* #return Datos
*/
public function setCelular($celular)
{
$this->celular = $celular;
return $this;
}
/**
* Get celular
*
* #return integer
*/
public function getCelular()
{
return $this->celular;
}
/**
* Set areaCel
*
* #param integer $areaCel
* #return Datos
*/
public function setAreaCel($areaCel)
{
$this->areaCel = $areaCel;
return $this;
}
/**
* Get areaCel
*
* #return integer
*/
public function getAreaCel()
{
return $this->areaCel;
}
/**
* Set email
*
* #param integer $email
* #return Datos
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return integer
*/
public function getEmail()
{
return $this->email;
}
/**
* Set personales
*
* #param string $personales
* #return Datos
*/
public function setPersonales($personales)
{
$this->personales = $personales;
return $this;
}
/**
* Get personales
*
* #return string
*/
public function getPersonales()
{
return $this->personales;
}
}
My DatosType:
<?php
namespace Proyecto\LavocBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class DatosType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('empresa');
$builder->add('cuit');
$builder->add('localidad');
$builder->add('calle');
$builder->add('altura');
$builder->add('areaTel');
$builder->add('telefono');
$builder->add('areaCel');
$builder->add('celular');
}
public function getName()
{
return 'datos_form';
}
}
The consultation on the controller but did not know how to do it. Now , do not like taking the data I receive and dump them in the form.
Thank you very much and sorry for the trouble
I think what you want to do can be done by following these steps :
Start by collecting your User data in a variable we will call $user
Then, give this $userto be hydrated by your form, like this :
$form = $this->createForm(new UserType(), $user);
Treat your form like you would normaly do. The values found in the entity should be automaticaly filled in your form.
Hope this helps.
Your action could be something like this:
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('LavocBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createForm(new UserType(), $entity);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
);
}

Lifecycle Callbacks not triggering in my embedded form

It would appear my lifecycle callbacks are not triggered when the form to upload my file is embedded in another form. If the upload form is on its own the lifecycle callbacks are triggered.
I have a form that creates a 'user' entity, for this user I have a one-on-one relationship with the 'ProfilePicture' entity which has the lifecycle callbacks, I want to upload the profilepicture file on the same form. I followed the "How to handle File Uploads" cookbook, but it doesn't explain how to handle embedded forms.
UserType
<?php
namespace CashBack\AdminBundle\Form\Type;
use CashBack\DefaultBundle\Entity\ProfilePicture;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
/* additional fields that should not be saved in this object need ->add('agreeWithTerms', null,array('mapped' => false))*/
$builder
->add('id','hidden',array('mapped' => false))
->add('username')
->add('password')
->add('firstname')
->add('lastname')
->add('email')
->add('gender')
->add('dateOfBirth','birthday')
->add('customrole')
->add('profilepicture', new ProfilePictureType())
->add('save', 'submit');
}
/* Identifier */
public function getName()
{
return 'User';
}
/* Makes sure the form doesn't need to guess the date type */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'CashBack\DefaultBundle\Entity\User',
'cascade_validation' => true,
));
}
}
ProfilePictureType
<?php
namespace CashBack\AdminBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProfilePictureType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
/* additional fields that should not be saved in this object need ->add('agreeWithTerms', null,array('mapped' => false))*/
$builder
->add('id','hidden',array('mapped' => false))
->add('file','file');
}
/* Identifier */
public function getName()
{
return 'ProfilePicture';
}
/* Makes sure the form doesn't need to guess the date type */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'CashBack\DefaultBundle\Entity\ProfilePicture',
));
}
}
ProfilePicture Entity
<?php
namespace CashBack\DefaultBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class ProfilePicture
{
/**
* #var integer
*
* #ORM\Column(name="Id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $path;
public function getAbsolutePath()
{
return null === $this->path
? null
: $this->getUploadRootDir() . '/' . $this->path;
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir() . '/' . $this->path;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'uploads/documents';
}
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
private $temp;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// check if we have an old image path
if (isset($this->path)) {
// store the old name to delete after the update
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
// do whatever you want to generate a unique name
$filename = sha1(uniqid(mt_rand(), true));
$this->path = $filename . '.' . $this->getFile()->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->getFile()) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getFile()->move($this->getUploadRootDir(), $this->path);
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->getUploadRootDir() . '/' . $this->temp);
// clear the temp image path
$this->temp = null;
}
$this->file = null;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set path
*
* #param string $path
*
* #return ProfilePicture
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="profilepicture")
* #ORM\JoinColumn(name="user_id", referencedColumnName="Id")
*/
protected $user;
/**
* Set user
*
* #param \CashBack\DefaultBundle\Entity\User $user
*
* #return ProfilePicture
*/
public function setUser(\CashBack\DefaultBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \CashBack\DefaultBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
User Entity
<?php
namespace CashBack\DefaultBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class User
{
/**
* #var string
*
* #ORM\Column(name="FirstName", type="string", length=10, nullable=true)
*/
private $firstname;
/**
* #var string
*
* #ORM\Column(name="LastName", type="string", length=20, nullable=true)
*/
private $lastname;
/**
* #var string
*
* #ORM\Column(name="Gender", type="string", length=1, nullable=true)
*/
private $gender;
/**
* #var string
*
* #ORM\Column(name="Email", type="string", length=50, nullable=false)
*/
private $email;
/**
* #var \DateTime
*
* #ORM\Column(name="DateOfBirth", type="date", nullable=false)
*/
private $dateofbirth;
/**
* #var string
*
* #ORM\Column(name="Username", type="string", length=50, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="Password", type="string", length=100, nullable=false)
*/
private $password;
/**
* #var integer
*
* #ORM\Column(name="Id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="CashBack\DefaultBundle\Entity\Tag", inversedBy="user")
* #ORM\JoinTable(name="user_tag",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="Id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="tag_id", referencedColumnName="Id")
* }
* )
*/
private $tag;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="CashBack\DefaultBundle\Entity\Customrole", inversedBy="user")
* #ORM\JoinTable(name="user_customrole",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="Id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="customrole_id", referencedColumnName="Id")
* }
* )
*/
private $customrole;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="CashBack\DefaultBundle\Entity\Shop", inversedBy="user")
* #ORM\JoinTable(name="user_shop",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="Id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="shop_id", referencedColumnName="Id")
* }
* )
*/
private $shop;
/**
* Constructor
*/
public function __construct()
{
$this->tag = new \Doctrine\Common\Collections\ArrayCollection();
$this->customrole = new \Doctrine\Common\Collections\ArrayCollection();
$this->shop = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set firstname
*
* #param string $firstname
*
* #return User
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
*
* #return User
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set gender
*
* #param string $gender
*
* #return User
*/
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender
*
* #return string
*/
public function getGender()
{
return $this->gender;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set dateofbirth
*
* #param \DateTime $dateofbirth
*
* #return User
*/
public function setDateofbirth($dateofbirth)
{
$this->dateofbirth = $dateofbirth;
return $this;
}
/**
* Get dateofbirth
*
* #return \DateTime
*/
public function getDateofbirth()
{
return $this->dateofbirth;
}
/**
* Set username
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add tag
*
* #param \CashBack\DefaultBundle\Entity\Tag $tag
*
* #return User
*/
public function addTag(\CashBack\DefaultBundle\Entity\Tag $tag)
{
$this->tag[] = $tag;
return $this;
}
/**
* Remove tag
*
* #param \CashBack\DefaultBundle\Entity\Tag $tag
*/
public function removeTag(\CashBack\DefaultBundle\Entity\Tag $tag)
{
$this->tag->removeElement($tag);
}
/**
* Get tag
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTag()
{
return $this->tag;
}
/**
* Add customrole
*
* #param \CashBack\DefaultBundle\Entity\Customrole $customrole
*
* #return User
*/
public function addCustomrole(\CashBack\DefaultBundle\Entity\Customrole $customrole)
{
$this->customrole[] = $customrole;
return $this;
}
/**
* Remove customrole
*
* #param \CashBack\DefaultBundle\Entity\Customrole $customrole
*/
public function removeCustomrole(\CashBack\DefaultBundle\Entity\Customrole $customrole)
{
$this->customrole->removeElement($customrole);
}
/**
* Get customrole
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCustomrole()
{
return $this->customrole;
}
/**
* Add shop
*
* #param \CashBack\DefaultBundle\Entity\Shop $shop
*
* #return User
*/
public function addShop(\CashBack\DefaultBundle\Entity\Shop $shop)
{
$this->shop[] = $shop;
return $this;
}
/**
* Remove shop
*
* #param \CashBack\DefaultBundle\Entity\Shop $shop
*/
public function removeShop(\CashBack\DefaultBundle\Entity\Shop $shop)
{
$this->shop->removeElement($shop);
}
/**
* Get shop
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getShop()
{
return $this->shop;
}
/** #ORM\OneToOne(targetEntity="ProfilePicture", mappedBy="user", cascade={"persist", "all"}) */
protected $profilepicture;
/**
* Set profilepicture
*
* #param \CashBack\DefaultBundle\Entity\ProfilePicture $profilepicture
*
* #return User
*/
public function setProfilepicture(\CashBack\DefaultBundle\Entity\ProfilePicture $profilepicture)
{
$this->profilepicture = $profilepicture;
$profilepicture->setUser($this);
return $this;
}
/**
* Get profilepicture
*
* #return \CashBack\DefaultBundle\Entity\ProfilePicture
*/
public function getProfilepicture()
{
return $this->profilepicture;
}
}
User controller
//adds a new entity from data received via Ajax, no redirect
public function addAjaxAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user);
$form->handleRequest($request);
$user = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
//prepare the response, e.g.
$response = array("code" => 100, "success" => true);
//you can return result as JSON , remember to 'use' Response!
return new Response(json_encode($response));
}
EDIT: when checking the profiler I saw that the following object is submitted in the form:
If i check the profiler I see the following object being submitted in the form: {"username":"test","password":"test","firstname":"test","lastname":"test","email":"test","gender":"t","dateOfBirth":{"month":"1","day":"1","year":"1902"},"customrole":["2"],"id":"","profilepicture":{"id":""},"_token":"YUDiZLi8dY6jtmEhZWk6ivnH3vsQIpnM_fxQ3ClJ2Gw"}
Profile picture is thus empty.