First of all: the error I'm getting is: Entities passed to the choice field must be managed
I have these entities:
- user (belongs to one or many teams)
- team (has one or 2 users)
- challenge (has 2 teams)
I'd like to build a ChallengeType form where a user can fill in the two users for the two teams and create the challenge. I think I need an embedded form here.
I've made a TeamType Form class: (I would expect to get a select box from this, where all users are listed)
<?php
namespace Tennisconnect\DashboardBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class TeamType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('players', 'entity', array(
'class' => 'TennisconnectUserBundle:User',
'multiple' => true
));
}
public function getName()
{
return 'team';
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Tennisconnect\DashboardBundle\Entity\Team');
}
}
This is the ChallengeType form class:
<?php
namespace Tennisconnect\DashboardBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class ChallengeType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('teams', 'collection', array('type' => new TeamType()));
}
public function getName()
{
return 'challenge';
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Tennisconnect\DashboardBundle\Entity\Challenge');
}
}
Challenge entity:
namespace Tennisconnect\DashboardBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Tennisconnect\DashboardBundle\Entity\Team;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="challenge")
*/
class Challenge
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Team", mappedBy="teams")
*/
protected $teams;
public function __construct()
{
$this->teams = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add teams
*
* #param Tennisconnect\DashboardBundle\Entity\Team $teams
*/
public function addTeam(Team $teams)
{
$this->teams[] = $teams;
}
/**
* Get teams
*
* #return Doctrine\Common\Collections\Collection
*/
public function getTeams()
{
return $this->teams;
}
}
Team entity:
namespace Tennisconnect\DashboardBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Tennisconnect\UserBundle\Entity\User;
use Tennisconnect\DashboardBundle\Entity\Challenge;
use Tennisconnect\DashboardBundle\Entity\Match;
/**
* #ORM\Entity
* #ORM\Table(name="team")
*/
class Team
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Tennisconnect\UserBundle\Entity\User", mappedBy="teams")
*/
protected $players;
/**
* #ORM\ManyToMany(targetEntity="challenge", inversedBy="teams", cascade= {"persist"})
*/
protected $challenges;
/**
* #ORM\ManyToMany(targetEntity="Match", inversedBy="teams")
*/
protected $matches;
public function __construct()
{
$this->players = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add players
*
* #param Tennisconnect\UserBundle\Entity\User $players
*/
public function addUser(User $players)
{
$this->players[] = $players;
}
/**
* Get players
*
* #return Doctrine\Common\Collections\Collection
*/
public function getPlayers()
{
return $this->players;
}
/**
* Add matches
*
* #param Tennisconnect\DashboardBundle\Entity\Match $matches
*/
public function addMatch(Match $matches)
{
$this->matches[] = $matches;
}
/**
* Get matches
*
* #return Doctrine\Common\Collections\Collection
*/
public function getMatches()
{
return $this->matches;
}
/**
* Add challenges
*
* #param Tennisconnect\DashboardBundle\Entity\challenge $challenges
*/
public function addchallenge(challenge $challenges)
{
$this->challenges[] = $challenges;
}
/**
* Get challenges
*
* #return Doctrine\Common\Collections\Collection
*/
public function getChallenges()
{
return $this->challenges;
}
}
Challenge controller:
class ChallengeController extends Controller
{
public function newAction()
{
$challenge = new Challenge();
$form = $this->createForm(new ChallengeType(), $challenge);
return $this->render('TennisconnectDashboardBundle:Challenge:new.html.twig', array('form' => $form->createView()));
}
}
You've created forms that are displaying a ManyToMany collection; set the multiple option in your formbuilder for those widgets to true (it defaults false, which fundamentally conflicts with a ToMany relationship).
If you have the error Entities passed to the choice field must be managed. Maybe persist them in the entity manager? with a ManyToMany relationship between 2 entities, when using a form type, it may come from your entity constructor :
If your form is "TeamType", try to remove the ArrayCollection initialization of your "Team" entity.
Your Team class become :
namespace Tennisconnect\DashboardBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Tennisconnect\UserBundle\Entity\User;
use Tennisconnect\DashboardBundle\Entity\Challenge;
use Tennisconnect\DashboardBundle\Entity\Match;
/**
* #ORM\Entity
* #ORM\Table(name="team")
*/
class Team
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Tennisconnect\UserBundle\Entity\User", mappedBy="teams")
*/
protected $players;
/**
* #ORM\ManyToMany(targetEntity="challenge", inversedBy="teams", cascade= {"persist"})
*/
protected $challenges;
/**
* #ORM\ManyToMany(targetEntity="Match", inversedBy="teams")
*/
protected $matches;
public function __construct()
{
// REMOVE $this->players = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add players
*
* #param Tennisconnect\UserBundle\Entity\User $players
*/
public function addUser(User $players)
{
$this->players[] = $players;
}
/**
* Get players
*
* #return Doctrine\Common\Collections\Collection
*/
public function getPlayers()
{
return $this->players;
}
/**
* Add matches
*
* #param Tennisconnect\DashboardBundle\Entity\Match $matches
*/
public function addMatch(Match $matches)
{
$this->matches[] = $matches;
}
/**
* Get matches
*
* #return Doctrine\Common\Collections\Collection
*/
public function getMatches()
{
return $this->matches;
}
/**
* Add challenges
*
* #param Tennisconnect\DashboardBundle\Entity\challenge $challenges
*/
public function addchallenge(challenge $challenges)
{
$this->challenges[] = $challenges;
}
/**
* Get challenges
*
* #return Doctrine\Common\Collections\Collection
*/
public function getChallenges()
{
return $this->challenges;
}
}
The problem is solved.
I had to add the "allow_add" option to my collection in the ChallengeType class.
The challenge controller class needed some editing too. I added 2 teams to the Challenge object before passing it through to the form.
Related
Thank you all for your answers from now. ThatÅ› the question. I have a symfony 2 app with two entities (Tasks and Products). When i tried to find (findBy,findOneBy,findAll) a product it returns an empty array.
Tasks Entity
<?php
namespace pablo\UserBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Task
*
* #ORM\Table(name="tasks")
* #ORM\Entity(repositoryClass="pablo\UserBundle\Repository\TaskRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Task
{
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="tasks")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $user;
/**
* #ORM\ManyToOne(targetEntity="Product", inversedBy="task")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $product;
public function __construct()
{
$this->tasks = new ArrayCollection();
}
/**
* Set product
*
* #param \pablo\UserBundle\Entity\Product $product
*
* #return Task
*/
public function setProduct(\pablo\UserBundle\Entity\Product $product = null)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return \pablo\UserBundle\Entity\Product
*/
public function getProduct()
{
return $this->product;
}
/**
* #return ArrayCollection
*/
public function getTasks()
{
return $this->tasks;
}
/**
* #param ArrayCollection $tasks
*/
public function setTasks($tasks)
{
$this->tasks = $tasks;
}
And Products Entity
<?php
namespace pablo\UserBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Products
*
* #ORM\Table(name="products")
* #ORM\Entity(repositoryClass="pablo\UserBundle\Repository\ProductsRepository")
* #UniqueEntity("productsName")
*/
class Product
{
/**
* #ORM\OneToMany(targetEntity="Task", mappedBy="product")
*/
protected $task;
/**
* #ORM\OneToMany(targetEntity="Publicaciones", mappedBy="product")
*/
protected $publicaciones;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="products_name", type="string", length=255)
* #Assert\NotBlank()
*/
private $productsName;
public function __construct()
{
$this->task = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set productsName
*
* #param string $productsName
*
* #return Product
*/
public function setProductsName($productsName)
{
$this->productsName = $productsName;
return $this;
}
/**
* Get productsName
*
* #return string
*/
public function getProductsName()
{
return $this->productsName;
}
public function __toString() {
return $this->productsName;
}
/**
* Get task
*
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getTask()
{
return $this->task;
}
/**
* Set task
*
* #param \Doctrine\Common\Collections\ArrayCollection $typeSponsor
*
* #return Task
*/
public function setTask($task)
{
$this->task = $task;
}
/**
* #return mixed
*/
public function getPublicaciones()
{
return $this->publicaciones;
}
/**
* #param mixed $publicaciones
*/
public function setPublicaciones($publicaciones)
{
$this->publicaciones = $publicaciones;
}
}
Now, when i tried to find a product from controller it returns an empty array ({}). I can't see what is wrong with this.
$productId = '18';
$product = $this->get('doctrine.orm.default_entity_manager')->getRepository('pabloUserBundle:Product')->find($productId);
Actually you have a result, it just is an empty object because you have not defined which of the properties should be printed.
The best solution is for your entity to implement JsonSerializable.
class Product implements \JsonSerializable
{
...
public function jsonSerialize()
{
return [
"id"=> $this->getId(),
"name" => $this->getProductsName()
];
}
Now it knows what it should print when converting the class to json object.
If you want the task collection also, implement JsonSerializable for the Task Entity and add in Product Entity:
public function jsonSerialize()
{
return [
"id"=> $this->getId(),
"name" => $this->getProductsName(),
"task" => $this->getTask()->toArray()
];
}
The JsonSerializable interface
A User has many Games.
A Game can Belong to many Users.
I have a form with a list of games, I want the list of Games to be added to the current logged User.
When I submit the form nothing happens, I want at least 1 record to be added to users_games:
Update:
Added User entity
FormType addGameToUserType:
namespace AppBundle\Form;
use AppBundle\Entity\Game;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class addGameToUserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('game', EntityType::class, [
'class' => 'AppBundle:Game',
'choice_label' => function ($game) {
return $game->getName();
},
'multiple' => true,
'expanded' => false,
]);
}
public function configureOptions(OptionsResolver $resolver)
{
}
public function getBlockPrefix()
{
return 'app_bundleadd_game_to_user';
}
}
UserController addGameAction:
/**
* Adds game(s) to current user.
*
* #Route("user/game/add", name="game_add")
* #Method({"GET", "POST"})
*/
public function addGameAction(Request $request)
{
/** #var $form */
$form = $this->createForm('AppBundle\Form\addGameToUserType');
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
echo $form->get('game')->getData();
$em = $this->getDoctrine()->getManager();
/** #var $game */
$game = new Game();
$game->getId();
/** #var User $userObject */
$userObject = $this->getUser();
$user = $em->getRepository('AppBundle:User')
->find(['id' => $userObject->getId()]);
$game->addGameUser($user);
$em->persist($user);
$em->flush();
}
return $this->render('user/addGame.html.twig', array(
'form' => $form->createView()
));
}
Game entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Game
*
* #ORM\Table(name="game")
* #ORM\Entity(repositoryClass="AppBundle\Repository\GameRepository")
*/
class Game
{
/**
* #ORM\OneToMany(targetEntity="PlayLog", mappedBy="game")
* #ORM\OrderBy({"date" = "DESC"})
*
*/
private $playlogs;
private $users;
/**
* #return ArrayCollection
*/
public function getUsers()
{
return $this->users;
}
/**
* #param ArrayCollection $users
*/
public function setUsers($users)
{
$this->users = $users;
}
// private $categories;
public function __construct()
{
$this->playlogs = new ArrayCollection();
$this->users = new ArrayCollection();
}
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(
* min = "3",
* max = "100"
* )
* #ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Game
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #return mixed
*/
public function getPlaylogs()
{
return $this->playlogs;
}
/**
* #param mixed $playlogs
*/
public function setPlaylogs($playlogs)
{
$this->playlogs = $playlogs;
}
public function addPlayLog(PlayLog $playlog)
{
$this->playlog->add($playlog);
$playlog->setPlayLogs($this);
}
public function addGameUser(User $user){
$this->users[] = $user;
}
}
User entity:
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\ManyToMany(targetEntity="Game")
*
* #ORM\JoinTable(name="users_games",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="game_id", referencedColumnName="id")}
* )
*/
private $games;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\PlayLog", mappedBy="user")
*
*/
private $playlogs;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
public function __construct()
{
$this->games = new ArrayCollection();
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #return mixed
*/
public function getGames()
{
return $this->games;
}
/**
* #param mixed $games
*/
public function setGames($games)
{
$this->games = $games;
}
public function addGame(Game $game)
{
// $this->games->add($game);
$this->games[] = $game;
return $this;
}
public function removeGame(Game $game)
{
$this->games->removeElement($game);
}
/**
* #return mixed
*/
public function getPlaylogs()
{
return $this->playlogs;
}
/**
* #param mixed $playlogs
*/
public function setPlaylogs($playlogs)
{
$this->playlogs = $playlogs;
}
public function addPlayLog(PlayLog $playlog)
{
$this->playlog->add($playlog);
$playlog->setPlayLogs($this);
}
}
I have two Entities
Employee and FreeDay
One employee can have one or more free days. The free days are defined as day of the week so Monday => 1, Tuesday => 2 etc..
In the Employee Form View I would like to show the FreeDay entity as checkbox list like this:
Days Form View
But I got this error:
Warning: spl_object_hash() expects parameter 1 to be object, integer given
I'm really confused and I don't know how to get out of this issue.
The entity code is the following:
Employee Entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Employee
*
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
*/
class Employee
{
/**
* #ORM\OneToMany(targetEntity="FreeDay", mappedBy="employee", cascade={"persist","remove"},orphanRemoval=true)
*/
private $freedays;
/**
* Constructor
*/
public function __construct()
{
$this->freedays = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add freedays
*
* #param \AppBundle\Entity\Free $freeday
*
* #return Employee
*/
public function addFreeDay(\AppBundle\Entity\FreeDay $freeday)
{
$this->freedays[] = $freeday;
return $this;
}
/**
* Remove freeday
*
* #param \AppBundle\Entity\FreeDay $freeday
*/
public function removeFreeDay(\AppBundle\Entity\FreeDay $freeday)
{
$this->freedays->removeElement($freeday);
}
/**
* Get freeday
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFreeDays()
{
return $this->freedays;
}
}
Free Day Entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
class FreeDay
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
* #ORM\ManyToOne(targetEntity="Employee", inversedBy="freedays")
* #ORM\JoinColumn(name="employee_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $employee;
/**
* #var int
*
* #ORM\Column(name="day", type="integer")
*/
private $day;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set day
*
* #param integer $day
*
* #return FreeDay
*/
public function setDay($day)
{
$this->day = $day;
return $this;
}
/**
* Get day
*
* #return int
*/
public function getDay()
{
return $this->day;
}
/**
* Set employee
*
* #param \AppBundle\Entity\Employee $employee
*
* #return FreeDay
*/
public function setEmployee(\AppBundle\Entity\Employee $employee = null)
{
$this->employee = $employee;
return $this;
}
/**
* Get employee
*
* #return \AppBundle\Entity\Employee
*/
public function getEmployee()
{
return $this->employee;
}
EmployeeType.php
class EmployeeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('freedays', EntityType::class, array(
'class'=>'AppBundle:FreeDay',
'choices'=>$this->getDays(),
'expanded'=>true,
'multiple'=>true
))
->add('save', SubmitType::class, array('label' => 'Salva'))
;
}
private function getDays() {
return array(
'Monday'=>1,
'Tuesday'=>2,
'Wednesday'=>3,
'Thursday'=>4,
'Friday'=>5,
'Saturday'=>6,
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Employee',
));
}
}
Using the entity option in your form builder requires the options to be objects of that entity, see here in the symfony documentation: http://symfony.com/doc/current/reference/forms/types/entity.html#using-choices
as you're passing an array to it you will always come across this error.
to achieve what you outline in your question you will need to have the freedays in your database with the relevant id and name like you list in your getDays function, so Monday will have an id in your database of 1.
if you just want all the options see this section of the documentation: http://symfony.com/doc/current/reference/forms/types/entity.html#basic-usage
however if you want filter the results you will need a query builder, described here in the documentation: http://symfony.com/doc/current/reference/forms/types/entity.html#using-a-custom-query-for-the-entities
Please let me know if this doesn't work for you or I've misunderstood the question.
Ok, so I am trying to save User to users table in my database and User info like name, surname to user_info table, using FosUserBundle what I have now is OneToOne bidirectional relation between these tables, form which save User and User info correctly but user_id in user_info table is always null I am trying to do this since 4 hours and now I have no idea what to do.
Edit:
I've managed it myself, didn't need bidirectional relation, will mark changes in files
Entity Users
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Entity\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Users
* #ORM\Entity(repositoryClass="AppBundle\Entity\UsersRepository")
* #ORM\Table()
* #ORM\Entity
*/
class Users extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
//don't need mappedBy option and that is whole relation statement
/**
* #ORM\OneToOne(targetEntity="UserInfo", //mappedBy="user", cascade={"persist","remove"})
*/
private $profil;
public function __construct(){
parent::__construct();
}
/**
* Set profil
*
* #param \AppBundle\Entity\UserInfo $profil
*
* #return Users
*/
public function setProfil(\AppBundle\Entity\UserInfo $profil = null)
{
$this->profil = $profil;
return $this;
}
/**
* Get profil
*
* #return \AppBundle\Entity\UserInfo
*/
public function getProfil()
{
return $this->profil;
}
}
UserInfo entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* UserInfo
*
* #ORM\Table()
* #ORM\Entity
*/
class UserInfo
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="user_name", type="string", length=255)
*/
private $userName;
/**
* #var string
* #ORM\Column(name="user_surname", type="string", length=255)
*/
private $userSurname;
/**
* #var integer
* #ORM\Column(name="blood_donated")
*/
private $bloodDonated;
/**
* Get id
*
* #return integer
*/
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set userName
*
* #param string $userName
*
* #return UserInfo
*/
public function setUserName($userName)
{
$this->userName = $userName;
return $this;
}
/**
* Get userName
*
* #return string
*/
public function getUserName()
{
return $this->userName;
}
/**
* Set userSurname
*
* #param string $userSurname
*
* #return UserInfo
*/
public function setUserSurname($userSurname)
{
$this->userSurname = $userSurname;
return $this;
}
/**
* Get userSurname
*
* #return string
*/
public function getUserSurname()
{
return $this->userSurname;
}
/**
* Set bloodDonated
*
* #param string $bloodDonated
*
* #return UserInfo
*/
public function setBloodDonated($bloodDonated)
{
$this->bloodDonated = $bloodDonated;
return $this;
}
/**
* Get bloodDonated
*
* #return string
*/
public function getBloodDonated()
{
return $this->bloodDonated;
}
}
And forms:
RegistrationFormType:
namespace UsersBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use AppBundle\Form\UserInfoType as UserInfoType;
class RegistrationFormType extends BaseType{
public function buildForm(FormBuilderInterface $builder, array $options){
parent::buildForm($builder, $options);
//adding profil hidden field to set profil in table, here whole magic happens at $builder -> add('profil','hidden')
$builder ->add('profil','hidden')
->add('profil', new UserInfoType(), array('data_class' => 'AppBundle\Entity\UserInfo'))
;
}
public function getName()
{
return 'my_user_registration';
}
}
and UserInfoType:
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserInfoType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('userName')
->add('userSurname')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\UserInfo'
));
}
/**
* #return string
*/
public function getName()
{
return 'appbundle_userinfo';
}
}
Edit So I needed 2 changes actually add profil input to form and fix my relation between tables, hope it will help someone
i'm new in symfony, i created a small DB schema attached:
Email Class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Email
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\EmailRepository")
*/
class Email extends Service
{
/**
* #var string
*
* #ORM\Column(name="emailAddress", type="string", length=255)
*/
private $emailAddress;
/**
* Set emailAddress
*
* #param string $emailAddress
*
* #return Email
*/
public function setEmailAddress($emailAddress)
{
$this->emailAddress = $emailAddress;
return $this;
}
/**
* Get emailAddress
*
* #return string
*/
public function getEmailAddress()
{
return $this->emailAddress;
}
}
and my service class:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Service
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\ServiceRepository")
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="type", type="string")
* #ORM\DiscriminatorMap({"newsletter" = "Newsletter", "email" = "Email", "service" = "Service"})
*
*/
class Service
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="serviceTitle", type="string", length=255)
*/
private $serviceTitle;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set serviceTitle
*
* #param string $serviceTitle
*
* #return Service
*/
public function setServiceTitle($serviceTitle)
{
$this->serviceTitle = $serviceTitle;
return $this;
}
/**
* Get serviceTitle
*
* #return string
*/
public function getServiceTitle()
{
return $this->serviceTitle;
}
/**
* #ORM\ManyToOne(targetEntity="Service", inversedBy="children")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Service", mappedBy="parent")
*/
private $children;
/**
* Constructor
*/
public function __construct()
{
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set parent
*
* #param \AppBundle\Entity\Service $parent
*
* #return Service
*/
public function setParent(\AppBundle\Entity\Service $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return \AppBundle\Entity\Service
*/
public function getParent()
{
return $this->parent;
}
/**
* Add child
*
* #param \AppBundle\Entity\Service $child
*
* #return Service
*/
public function addChild(\AppBundle\Entity\Service $child)
{
$this->children[] = $child;
return $this;
}
/**
* Remove child
*
* #param \AppBundle\Entity\Service $child
*/
public function removeChild(\AppBundle\Entity\Service $child)
{
$this->children->removeElement($child);
}
/**
* Get children
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
}
then i generate crud for email, it was working perfect, now i actually want to add two fields for service (SERVICE TITLE, and PARENT SERVICE)
what i did, i just opened email type form and added two fields for (service title and Parent service):
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class EmailType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('emailAddress')
->add('serviceTitle')
->add('parent')
;
}
after saving, when i create new email service browser return exception:
Catchable Fatal Error: Object of class AppBundle\Entity\Email could not be converted to string
right now i just add parent ID in text box (input type text) but actually i want to use (choice lise) from which user can set a parent service at the time of creating new service, and that choice list having all previously created services
add a __toString() method to your email class:
public function __toString()
{
return $this->emailAddress;
}