Symfony 3 : Check if I am logged in - php

I would like to check if I am logged in when I login with a form, but I can't find my anwser and I don't understand the tutorial on symfony website... I try to follow this : http://symfony.com/doc/current/security.html , but I don't want to do with a "HTTP basic authentication", but with my symfony form.
Here is my user class :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Player
*
* #ORM\Table(name="player")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PlayerRepository")
*/
class Player implements UserInterface, \Serializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="pseudo", type="string", length=255, unique=true)
*/
private $pseudo;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
protected $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
protected $password;
/**
* #var \DateTime
*
* #ORM\Column(name="date_log", type="datetime", nullable=true)
*/
private $dateLog;
/**
* #ORM\OneToMany(targetEntity="Characters", mappedBy="player")
*/
private $characters;
public function __construct(){
$this->characters = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set pseudo
*
* #param string $pseudo
*
* #return Player
*/
public function setPseudo($pseudo)
{
$this->pseudo = $pseudo;
return $this;
}
/**
* Get pseudo
*
* #return string
*/
public function getPseudo()
{
return $this->pseudo;
}
/**
* Set email
*
* #param string $email
*
* #return Player
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
*
* #return Player
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set dateLog
*
* #param \DateTime $dateLog
*
* #return Player
*/
public function setDateLog($date_log)
{
$this->dateLog = $date_log;
return $this;
}
/**
* Get dateLog
*
* #return \DateTime
*/
public function getDateLog()
{
return $this->dateLog;
}
/**
* Set Characters
*
* #param array $characters
*
* #return Characters
*/
public function setCharacters($characters)
{
$this->characters = $characters;
return $this;
}
/**
* Get characters
*
* #return array
*/
public function getCharacters()
{
return $this->characters;
}
/**
* Add character
*
* #param \AppBundle\Entity\Characters $character
*
* #return Player
*/
public function addCharacter(\AppBundle\Entity\Characters $character)
{
$this->characters[] = $character;
return $this;
}
/**
* Remove character
*
* #param \AppBundle\Entity\Characters $character
*/
public function removeCharacter(\AppBundle\Entity\Characters $character)
{
$this->characters->removeElement($character);
}
public function getUsername()
{
return $this->pseudo;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->pseudo,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->pseudo,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
}
Then my login form (it work well, I am just not able to check if anybody is connected):
public function indexAction(Request $request)
{
$player = new Player;
$form = $this->createFormBuilder($player)
->add('email', TextType::class, array('label' => 'Email :'))
->add('password', PasswordType::class, array('label' => 'Mot de passe :'))
->add('login', SubmitType::class, array('label' => 'Login'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$password = $form['password']->getData();
$email = $form['email']->getData();
$encoded_pass = sha1($form['password']->getData());
$date = date_create();
$player = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findOneByEmail($email);
$pass_check = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findByPassword($encoded_pass);
if(!$player)
{
//return $this->redirectToRoute('registration');
}
else
{
$pseudo = $this->getDoctrine()
->getRepository('AppBundle:Player')
->findOneByEmail($email)->getPseudo();
$player->setDateLog($date);
$em = $this->getDoctrine()->getManager();
$em->persist($player);
$em->flush(); // insère dans la BD
return $this->redirectToRoute('accueil', array('pseudo' => $pseudo));
}
}
return $this->render('Sko/menu.html.twig', array('form' => $form->createView()));
}
EDIT : I don't want to encode my password because I already do it (even if it is not 100% securised)
EDIT2 : Well I think I can't do that, when I saw the tutoriel, I saw that on their symfony toolbar, we can seethere is the role of the user instead of an anonymous user, but they didn't do this dynamically. Maybe I can't do it dynamically so I need to send user information each time I change page
EDIT3 : I will clarify my question : How to change the token class when I login?

You dont need to create your token, but encoder like described in this answer
After that you can log in programmatically with this code
$token = new UsernamePasswordToken($player, $player->getPassword(), "main");
$event = new InteractiveLoginEvent(new Request(), $token);
$this->container->get("event_dispatcher")->dispatch("security.interactive_login", $event);
$this->container->get("security.token_storage")->setToken($token);
Now you can use standard symfony security functionality to check if user logged in etc

Related

Undefined method "login". The method name must start with either findBy, findOneBy or countBy

Hello everyone! I am doing authorization on laminas + doctrine
In this method, I request the repository of the user's entity and refer to the login method, at the exit I get an error. Also here I use the adapter design pattern, but this is not so important
public function indexAction()
{
$em = $this->em;
$form = new LoginForm();
$request = $this->getRequest();
if($request->isPost())
{
$form->setData($request->getPost());
if($form->isValid())
{
$user = $form->getData();
$authResult = $em->getRepository('\Blog\Entity\User')->login($user, $this->container);
if($authResult->getCode() != \Laminas\Authentication\Result::SUCCESS)
{
foreach ($authResult->getMessages() as $message)
{
$messages .= "$message\n";
}
}else {
return [];
}
}
}
return ['form' => $form, 'messages' => $messages];
}
This is my entity user:
<?php
namespace Blog\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table(name="user")\
* #ORM\Entity(repositoryClass="Blog\Entity\Repository\UserRepository")
* #ORM\Entity
*/
class User
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=100, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=100, nullable=false)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=60, nullable=false)
*/
private $email;
/**
* #var string|null
*
* #ORM\Column(name="password_salt", type="string", length=100, nullable=true)
*/
private $passwordSalt;
/**
* #var \DateTime
*
* #ORM\Column(name="user_registration_date", type="datetime", nullable=false)
*/
private $userRegistrationDate;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* 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;
}
/**
* 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 passwordSalt.
*
* #param string|null $passwordSalt
*
* #return User
*/
public function setPasswordSalt($passwordSalt = null)
{
$this->passwordSalt = $passwordSalt;
return $this;
}
/**
* Get passwordSalt.
*
* #return string|null
*/
public function getPasswordSalt()
{
return $this->passwordSalt;
}
/**
* Set userRegistrationDate.
*
* #param \DateTime $userRegistrationDate
*
* #return User
*/
public function setUserRegistrationDate($userRegistrationDate)
{
$this->userRegistrationDate = $userRegistrationDate;
return $this;
}
/**
* Get userRegistrationDate.
*
* #return \DateTime
*/
public function getUserRegistrationDate()
{
return $this->userRegistrationDate;
}
}
Here is my repository where my login method is login:
<?php
namespace Blog\Entity\Repository;
use Doctrine\ORM\EntityRepository;
use Laminas\Db\Adapter\Adapter;
class UserRepository extends EntityRepository
{
public function login(\Blog\Entity\User $user, $sm)
{
$authService = $sm->get(\Laminas\Authentication\AuthenticationService::class);
$adapter = $authService->getAdapter();
$adapter->setIdentityValue($user->getUsername());
$adapter->setCredentialValue($user->getPassword());
$authResult = $authService->authenticate();
$identity = null;
if($authService->isValid())
{
$identity = $authResult->getIdentity();
$authService->getStorage()->write($identity);
}
return $authResult;
}
}

Could not determine access type for property "roles"

I'm getting the following error when trying to submit the following form
I figured the error must be from the fact that the property for roles within User is userRoles and not roles. I'd like to know if there is a way to map the EntityType field to a property in Users I looked at this Answer but it does not seem to be the proper way to solve this problem, it is more of a work around.
class UserEditType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('roles', EntityType::class, array('multiple'=> true, 'class' => 'AuthBundle:Role', 'choice_label' => 'slug','attr' => array('class'=>'form-control')))
->add('email', EmailType::class, array('attr' => array('class'=>'form-control')))
->add('username', TextType::class, array('attr' => array('class'=>'form-control')))
->add('active', CheckboxType::class, array('attr' => array('class'=>'checkbox')));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => User::class,
));
}
}
The User Class
class User implements AdvancedUserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #Assert\Length(max=4096)
* #Assert\Length(min=8)
*/
private $plainPassword;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=240, nullable=true)
*/
private $profilePicture;
/**
* #ORM\Column(type="string", length=180, unique=true, options={"default" : "default.png"})
*/
private $email;
/**
* #ORM\Column(name="is_active", type="boolean", options={"default" : 0})
*/
private $isActive;
/**
* #ORM\ManyToMany(targetEntity="Role")
* #ORM\JoinTable(name="user_role",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*
* #var ArrayCollection $userRoles
*/
protected $userRoles;
public function __construct()
{
$this->userRoles = new ArrayCollection();
}
public function getUsername()
{
return $this->username;
}
//deprecated bcrypt does not require salt
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function isActive()
{
return $this->isActive;
}
public function getPassword()
{
return $this->password;
}
public function getplainPassword()
{
return $this->plainPassword;
}
public function getPicture()
{
return $this->profilePicture;
}
public function getRoles()
{
return $this->getUserRoles()->toArray();
}
public function eraseCredentials()
{
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
$this->isActive,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
$this->isActive,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPlainPassword($password)
{
$this->plainPassword = $password;
return $this;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set profilePicture
*
* #param string $profilePicture
*
* #return User
*/
public function setProfilePicture($profilePicture)
{
$this->profilePicture = $profilePicture;
return $this;
}
/**
* Get profilePicture
*
* #return string
*/
public function getProfilePicture()
{
return $this->profilePicture;
}
/**
* 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 isActive
*
* #param boolean $isActive
*
* #return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
/**
* Add userRole
*
* #param \AuthBundle\Entity\Role $userRole
*
* #return User
*/
public function addUserRole(\AuthBundle\Entity\Role $userRole)
{
$this->userRoles[] = $userRole;
return $this;
}
/**
* Remove userRole
*
* #param \AuthBundle\Entity\Role $userRole
*/
public function removeUserRole(\AuthBundle\Entity\Role $userRole)
{
$this->userRoles->removeElement($userRole);
}
/**
* Get userRoles
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUserRoles()
{
return $this->userRoles;
}
}
The Role Class
class Role implements RoleInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
* #var integer $id
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #var string $name
*/
protected $name;
/**
* #ORM\Column(type="string", length=255)
*
* #var string $slug
*/
protected $slug;
/**
* #ORM\Column(type="datetime", name="created_at")
*
* #var DateTime $createdAt
*/
protected $createdAt;
/**
* #ORM\ManyToMany(targetEntity="AuthBundle\Entity\User")
*/
protected $users;
/**
*
*/
public function __construct()
{
$this->users = new ArrayCollection();
$this->createdAt = new \DateTime();
}
/**
*
*
* #return integer The id.
*/
public function getId()
{
return $this->id;
}
/**
*
*
* #return string The name.
*/
public function getName()
{
return $this->name;
}
/**
*
*
* #param string $value The name.
*/
public function setName($value)
{
$this->name = $value;
}
/**
*
*
* #return string The name.
*/
public function getSlug()
{
return $this->slug;
}
/**
*
*
* #param string $value The name.
*/
public function setSlug($value)
{
$this->slug = $value;
}
/**
*
*
* #return DateTime A DateTime object.
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* RoleInterface.
*
* #return string The role.
*/
public function getRole()
{
return $this->getName();
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Role
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Add user
*
* #param \AuthBundle\Entity\User $user
*
* #return Role
*/
public function addUser(\AuthBundle\Entity\User $user)
{
$this->users[] = $user;
return $this;
}
/**
* Remove user
*
* #param \AuthBundle\Entity\User $user
*/
public function removeUser(\AuthBundle\Entity\User $user)
{
$this->users->removeElement($user);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}

Adding many to many relationship into database Symfony

I'm trying to add new user with ManyToMany relationship with group, but only user is saving in database
this is my
User.php
/**
* Acme\UserBundle\Entity\User
*
* #ORM\Table(name="User")
* #ORM\Entity(repositoryClass="Acme\UserBundle\Entity\UserRepository")
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="username", type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(name="salt", type="string", length=40)
*/
private $salt;
/**
* #ORM\Column(name="password", type="string", length=40)
*/
private $password;
/**
* #ORM\Column(name="email", type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(name="isActive", type="boolean")
*/
private $isActive;
/**
* #ORM\ManyToMany(targetEntity="Group", inversedBy="users")
*
* #ORM\JoinTable(name="user_group",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*
*/
private $groups;
public function __construct()
{
$this->isActive = true;
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
$this->groups = new ArrayCollection();
}
/**
* #inheritDoc
*/
public function getRoles()
{
$roles = array();
foreach ($this->groups as $role) {
$roles[] = $role->getRole();
}
return $roles;
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
/*
* ! Don't serialize $roles field !
*/
return \json_encode(array(
$this->id,
$this->username,
$this->email,
$this->salt,
$this->password,
$this->isActive
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->email,
$this->salt,
$this->password,
$this->isActive
) = \json_decode($serialized);
}
public function eraseCredentials()
{
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
return $this->salt;
}
public function getPassword()
{
return $this->password;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set salt
*
* #param string $salt
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* 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 isActive
*
* #param boolean $isActive
* #return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Add groups
*
* #param \Acme\UserBundle\Entity\Group $groups
* #return User
*/
public function addGroup(\Acme\UserBundle\Entity\Group $groups)
{
$groups->addUser($this);
$this->groups -> add($groups);
return $this->groups;
}
/**
* Remove groups
*
* #param \Acme\UserBundle\Entity\Group $groups
*/
public function removeGroup(\Acme\UserBundle\Entity\Group $groups)
{
$this->groups->removeElement($groups);
}
/**
* Get groups
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getGroups()
{
return $this->groups;
}
}
my Group.php
<?php
namespace Acme\UserBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="groups")
* #ORM\Entity
*/
class Group implements RoleInterface, \Serializable
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/** #ORM\Column(name="name", type="string", length=30) */
private $name;
/** #ORM\Column(name="role", type="string", length=20, unique=true) */
private $role;
/** #ORM\ManyToMany(targetEntity="User", mappedBy="groups",cascade={"persist"}) */
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
// ... getters and setters for each property
/** #see RoleInterface */
public function getRole()
{
return $this->role;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
/*
* ! Don't serialize $users field !
*/
return \json_encode(array(
$this->id,
$this->role
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->role
) = \json_decode($serialized);
}
/**
* Set name
*
* #param string $name
* #return Group
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set role
*
* #param string $role
* #return Group
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Add users
*
* #param \Acme\UserBundle\Entity\User $users
* #return Group
*/
public function addUser(\Acme\UserBundle\Entity\User $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* #param \Acme\UserBundle\Entity\User $users
*/
public function removeUser(\Acme\UserBundle\Entity\User $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}
and fragment from my controller
public function newAction(Request $request)
{
$user = new User();
$form = $this->createFormBuilder($user)
->add('username', 'text')
->add('password', 'text')
->add('email', 'email')
->add('submit','submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$user=$form->getData();
$group=new Group();
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$user->setSalt(md5(time()));
$pass = $encoder->encodePassword($form->getData()->getPassword(), $user->getSalt());
$user->setPassword($pass);
$group->setRole('ROLE_USER');
$user->addGroup($group);
$em = $this->getDoctrine()->getManager();
$em->merge($user);
$em->flush();
return $this->redirect($this->generateUrl('login'));
}
return $this->render('AcmeUserBundle:User:new.html.twig', array(
'form' => $form->createView(),
));
in database i have 3 table : User, Group and user_group (user_id, group_id)
everything generated from entities. I can register new user but it isnt saving in user_group.
Thanks for any help.
Ps.Sorry for my poor english
From what i can tell, you're not saving your group. So because you're not saving it, there is no user_group to save, because your group doesn't exist in the database. However you'll have another problem once you do this because you have a unique constraint on the role field for your group, so you'll get a database error saying you have a duplicate once you try to register more than one person. You'll need to pull the group from the db instead of making a new one every time.
$group = $this->em->getRepository('Group')->findOneByRole('ROLE_USER');
$user->addGroup($group);
$em->persist($group);
$em->persist($user);
$em->flush();
Update your controller to contain:
$group = $em->getRepository('AcmeUserBundle:Group')->findOne(array('role' => 'ROLE_USER'));
$user->addGroup($group);
$em->persist($user);
$em->persist($group);
$em->flush();
You forgot to persist the Group entity in your code, so it didn't save any data.
By the way, I suggest using a UserService that handles all that logic instead of putting it all in your controllers.
Also, in your User.php, you can just do:
/**
* #ORM\ManyToMany(targetEntity="Group", inversedBy="user")
*/
protected $groups;
The #JoinColumn annotation is not required. If it is not specified the attributes name and referencedColumnName are inferred from the table and primary key names.

Combine Questionnaire with User entity in form - symfony2

I need to add questionnaire of multiple choice questions to my registration form. The questions and options are in two entities:
<?php
namespace Me\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Question
*
* #ORM\Table(name="question")
* #ORM\Entity(repositoryClass="Me\UserBundle\Entity\QuestionRepository")
*/
class Question
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="questionText", type="text")
*/
private $questionText;
/**
* #var boolean $expanded
*
* #ORM\Column(name="expanded", type="boolean")
*/
private $expanded;
/**
* #var boolean $multiple
*
* #ORM\Column(name="multiple", type="boolean")
*/
private $multiple;
/**
* #var Questionnaire $questionnaire
*
* #ORM\ManyToOne(targetEntity="Questionnaire", inversedBy="questions")
* #ORM\JoinColumn(name="questionnaire", referencedColumnName="id", onDelete="cascade")
*/
private $questionnaire;
/**
* #var \Doctrine\Common\Collections\ArrayCollection $options
*
* #ORM\OneToMany(targetEntity="Option", mappedBy="question", cascade={"all"})
*/
private $options;
public function __construct()
{
$this->expanded = false;
$this->multiple = false;
$this->options = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set questionText
*
* #param string $questionText
* #return Question
*/
public function setQuestionText($questionText)
{
$this->questionText = $questionText;
return $this;
}
/**
* Get questionText
*
* #return string
*/
public function getQuestionText()
{
return $this->questionText;
}
/**
* #param mixed $options
*/
public function setOptions($options)
{
$this->options[] = $options;
return $this;
}
/**
* #return mixed
*/
public function getOptions()
{
return $this->options;
}
function __toString()
{
return $this->getQuestionText();
}
/**
* #param boolean $expanded
*/
public function setExpanded($expanded)
{
$this->expanded = $expanded;
}
/**
* #return boolean
*/
public function getExpanded()
{
return $this->expanded;
}
/**
* #param boolean $multiple
*/
public function setMultiple($multiple)
{
$this->multiple = $multiple;
}
/**
* #return boolean
*/
public function getMultiple()
{
return $this->multiple;
}
/**
* #param \Me\UserBundle\Entity\Questionnaire $questionnaire
*/
public function setQuestionnaire($questionnaire)
{
$this->questionnaire = $questionnaire;
}
/**
* #return \Me\UserBundle\Entity\Questionnaire
*/
public function getQuestionnaire()
{
return $this->questionnaire;
}
}
and
<?php
namespace Me\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* QuestionOption
*
* #ORM\Table(name="option")
* #ORM\Entity(repositoryClass="Me\UserBundle\Entity\OptionRepository")
*/
class Option
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="questionId", type="integer")
*/
private $questionId;
/**
* #var string
*
* #ORM\Column(name="optionText", type="string", length=255)
*/
private $optionText;
/**
* #ORM\ManyToOne(targetEntity="Question", inversedBy="options")
* #ORM\JoinColumn(name="questionId", referencedColumnName="id", onDelete="cascade")
**/
private $question;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set optionText
*
* #param string $optionText
* #return Option
*/
public function setOptionText($optionText)
{
$this->optionText = $optionText;
return $this;
}
/**
* Get optionText
*
* #return string
*/
public function getOptionText()
{
return $this->optionText;
}
/**
* #return mixed
*/
public function getQuestion()
{
return $this->question;
}
/**
* #param mixed $question
*/
public function setQuestion($question)
{
$this->question = $question;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
function __toString()
{
return $this->getOptionText();
}
}
I also have a questionnaire entity, though I don't think I really need it because users won't be creating questionnaires, only filling the single questionnaire during registration.
My user entity:
<?php
namespace Me\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="Me\UserBundle\Entity\UserRepository")
*/
class User
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="firstName", type="string", length=50)
*/
private $firstName;
/**
* #var string
*
* #ORM\Column(name="middleInitial", type="string", length=50)
*/
private $middleInitial;
/**
* #var string
*
* #ORM\Column(name="lastName", type="string", length=50)
*/
private $lastName;
/**
* #var string
*
* #ORM\Column(name="homePhoneArea", type="string", length=3)
*/
private $homePhoneArea;
/**
* #var string
*
* #ORM\Column(name="homePhoneNumber", type="string", length=7)
*/
private $homePhoneNumber;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=50)
*/
private $email;
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*/
public $questions;
public function __construct()
{
$this->questions = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* 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 middleInitial
*
* #param string $middleInitial
* #return User
*/
public function setMiddleInitial($middleInitial)
{
$this->middleInitial = $middleInitial;
return $this;
}
/**
* Get middleInitial
*
* #return string
*/
public function getMiddleInitial()
{
return $this->middleInitial;
}
/**
* 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 homePhoneArea
*
* #param string $homePhoneArea
* #return User
*/
public function setHomePhoneArea($homePhoneArea)
{
$this->homePhoneArea = $homePhoneArea;
return $this;
}
/**
* Get homePhoneArea
*
* #return string
*/
public function getHomePhoneArea()
{
return $this->homePhoneArea;
}
/**
* Set homePhoneNumber
*
* #param string $homePhoneNumber
* #return User
*/
public function setHomePhoneNumber($homePhoneNumber)
{
$this->homePhoneNumber = $homePhoneNumber;
return $this;
}
/**
* Get homePhoneNumber
*
* #return string
*/
public function getHomePhoneNumber()
{
return $this->homePhoneNumber;
}
/**
* 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;
}
/**
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getQuestions()
{
return $this->questions;
}
}
My user controller:
public function newAction()
{
$user = new User();
$em = $this->getDoctrine()->getManager();
$questions = $em->getRepository('MeUserBundle:Question')->findAll();
if (!$questions) {
throw $this->createNotFoundException('Unable to find Questions.');
}
$builder = $this->createFormBuilder();
$optionEntities = array();
foreach ($questions as $question)
{
$options = array();
foreach ($question->getOptions() as $option)
{
$options[$option->getId()] = $option->getOptionText();
$optionEntities[$option->getId()] = $option;
}
$builder->add('question_'. $question->getId(), 'choice', array(
'label' => $question->getQuestionText(),
'expanded' => $question->getExpanded(),
'multiple' => $question->getMultiple(),
'choices' => $options
));
}
$user->getQuestions()->add($questions);
$form = $this->createForm(new MyFormType(), array('User' => $user));
return $this->render('MeUserBundle:User:new.html.twig', array(
'entity' => $user,
'form' => $form->createView(),
));
}
The form type as it stands today:
<?php
namespace Me\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class MyFormType extends AbstractType
{
protected $questions;
public function __construct( $questions)
{
$this->questions = $questions;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('questions', 'collection', array(
'type' => new QuestionType()
))
->add('firstName')
->add('middleInitial')
->add('lastName')
->add('homePhoneArea')
->add('homePhoneNumber')
->add('email')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
));
}
public function getName()
{
return 'myform_type';
}
}
This setup doesn't work to get the questions and their associated options, and display them in the same user creation form. I've seen instructions and docs for combining forms, but not creating forms with this kind of configuration. Any guidance would be appreciated.
I'm not sure if I've understood your question correctly but maybe this could help.
From what I see you're building the form(for questions) but you're not using it anywhere! The easiest way is to pass the questions(in your case $user->getQuestions() ) to the MyFormType and the add all the questions inside of the type.
So it would look like something like this
$this->createForm(new MyFormType($user->getQuestions()), array('User' => $user));
And inside your type
protected $questions;
public function __construct($questions)
{
$this->questions = $questions;
}
protected $questions;
public function __construct($questions)
{
$this->questions = $questions;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach ($this->questions as $question)
{
$options = array();
foreach ($question->getOptions() as $option)
{
$options[$option->getId()] = $option->getOptionText();
$optionEntities[$option->getId()] = $option;
}
$builder->add('question_'. $question->getId(), 'choice', array(
'label' => $question->getQuestionText(),
'expanded' => $question->getExpanded(),
'multiple' => $question->getMultiple(),
'choices' => $options
));
}
}
Edit 1
Why don't you try the following?
Add the method setQuestionnaire in User and create a type called QuestionnaireType which is responsible to create the whole questionnaire
In the UserType(sorry for the wrong names) add the QuestionnaireType as an embedded form
Once the user submits the data and you call the bind symfony will pass the whole questionnaire object to the created method so you can iterate over it and save the user's aswers!
Your users entity needs a relation to his $answers you should store in an $answers-field in your user entity, (look up "embedding collections")
Then in your controller that digests the form your store the values by $user->setAnswers(value)) and then you'll find the answers values in the users entity's $answers field ($user->getAnswers()).
ANd dont forget to add your getters and setters.
$php app/console doctrine:generate:entities BundleName:Entityname
At first you could add a setQuestions method in user, this method will receive an ArrayCollection.
Then have you got a look at http://symfony.com/doc/current/reference/forms/types/collection.html ?
And maybe you could ask yourself what does this form should display/do
Does it need to embbed a collection or a list of QuestionFormType could be ok?
Each time i have to do embedded form type, i draw sketches and activity diagram for being sure to not dive into a to complex form structure

symfony2 selected option

I'm making the user edit.
I want to view selected role of the current user by Users.role_id = UsersRole.id
The table Users has four columns (id,username,roleId,descriptions)
The table UsersRole has two columns (id,name)
Controller:
public function editAction($id) {
$user = $this->getDoctrine()
->getEntityManager()
->getRepository('TruckingMainBundle:Users')
->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find user id.');
}
$form = $this->createForm(new \Trucking\AdminBundle\Form\UserType(), $user);
$request = $this->getRequest();
//save data
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('tracking_admin_users'));
}
}
return $this->render('TruckingAdminBundle:user:edit.html.twig', array(
'id' => $id,
'form' => $form->createView()
)
);
}
UserType.php
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('roleId', 'entity', array(
'class' => 'TruckingMainBundle:UsersRole',
'property' => 'name'
))
->...->..
}
I don't know how to set selected (default) value in that list, I've been trying to do it for 5 hours ,but still no results I've used preferred_choices, query_builder -> where I can select by critreia(but i don't need that)
http://symfony.com/doc/current/reference/forms/types/entity.html
I can print my current user id -> print_r($user->getRoleId()); I already have it.
My 'Users' entity has connection with UserRole entity
Users entity
namespace Trucking\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Trucking\MainBundle\Entity\Users
*
* #ORM\Table(name="Users")
* #ORM\Entity
*/
class Users implements UserInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var string $password
*
* #ORM\Column(name="password", type="string", length=15)
*/
private $password;
/**
* #var string $username
*
* #ORM\Column(name="username", type="string", length=30)
*/
private $username;
/**
* #var string $description
*
* #ORM\Column(name="description", type="string", length=20)
*/
private $description;
/**
* #var string $permissions
*
* #ORM\Column(name="permissions", type="string", length=300)
*/
private $permissions;
/**
* #var \DateTime $date
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #var integer $role_id
*
* #ORM\Column(name="role_id", type="integer")
*/
private $role_id;
/**
* #var integer $company_id
*
* #ORM\Column(name="company_id", type="integer")
*/
private $company_id;
/**
* #ORM\ManyToMany(targetEntity="Company", inversedBy="users")
*
*/
protected $companies;
/**
* #ORM\OneToOne(targetEntity="UsersRole")
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
*/
protected $roles;
public function __construct() {
$this->companies = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set password
*
* #param string $password
* #return Users
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set username
*
* #param string $username
* #return Users
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set description
*
* #param string $description
* #return Users
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set permissions
*
* #param string $permissions
* #return Users
*/
public function setPermissions($permissions)
{
$this->permissions = $permissions;
return $this;
}
/**
* Get permissions
*
* #return string
*/
public function getPermissions()
{
return $this->permissions;
}
/**
* Set date
*
* #param \DateTime $date
* #return Users
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set role_id
*
* #param integer $role
* #return Users
*/
public function setRoleId($role_id)
{
$this->roleId = $role_id;
return $this;
}
/**
* Get role_id
*
* #return integer
*/
public function getRoleId()
{
return $this->role_id;
}
/**
* Set company_id
*
* #param Company $company_id
* #return Users
*/
public function setCompany(Company $company_id)
{
$this->company = $company_id;
return $this;
}
/**
* Get company_id
*
* #return integer
*/
public function getCompanyId()
{
return $this->company_id;
}
public function equals(UserInterface $user) {
return $this->getUsername() == $user->getUsername();
}
public function eraseCredentials() {
}
public function getRoles() {
return (array)$this->roles->getName();
}
public function setRoles($role) {
$this->roles = array($role);
}
public function getSalt() {
}
}
UsersRole entity
namespace Trucking\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* USERS_ROLE
*
* #ORM\Table(name="USERS_ROLE")
* #ORM\Entity
*/
class UsersRole
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=30)
*/
protected $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=200)
*/
protected $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return USERS_ROLE
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return USERS_ROLE
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
UserType (for form)
<?php
namespace Trucking\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints;
class UserType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add("username","text",array(
"label" => "Name",
'attr' => array(
'class' => 'input-xlarge',
),
'constraints' => new Constraints\Length(array('min' => 3))
))
->add('roleId', 'entity', array(
'class' => 'TruckingMainBundle:UsersRole',
"label" => "Roles",
'property' => 'name'
))
->add("description","text",array(
"label" => "Description",
'attr' => array(
'class' => 'input-xlarge'
),
'constraints' => new Constraints\NotBlank()
));
}
public function getName()
{
return 'trucing_adminbundle_usertype';
}
}
Set the property on your entity before you render the form:
if (!$user) {
throw $this->createNotFoundException('Unable to find user id.');
}
//THIS IS NEW
$theRole = getRoleEntityFromSomewhereItMakesSense();
$user->setRole($theRole); //Pass the role object, not the role's ID
$form = $this->createForm(new \Trucking\AdminBundle\Form\UserType(), $user);
$request = $this->getRequest();
When you generate a form, it gets automatically populated with the properties of the entity you are using.
EDIT
Change
->add('roleId', 'entity', array(
to
->add('roles', 'entity', array(
I don't get why you have roleId and roles at the same time.
Also change the following, since roles is a single element, not an array (you have a relation one-to-one on it, and should be one-to-many and reversed as many-to-one, but I guess it will also work)
public function getRoles() {
return $this->roles;
}
public function setRoles($role) {
$this->roles = $role;
}
There has been a problem with ORM JOINS. id to role_id
I've changed the mapping from One-To-One Bidirectional
to One-To-One, Unidirectional with Join Table.
Full code:
Users.php
<?php
namespace Trucking\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Trucking\MainBundle\Entity\Users
*
* #ORM\Table(name="Users")
* #ORM\Entity
*/
class Users implements UserInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var string $password
*
* #ORM\Column(name="password", type="string", length=15)
*/
protected $password;
/**
* #var string $username
*
* #ORM\Column(name="username", type="string", length=30)
*/
protected $username;
/**
* #var string $description
*
* #ORM\Column(name="description", type="string", length=20)
*/
protected $description;
/**
* #var string $permissions
*
* #ORM\Column(name="permissions", type="string", length=300)
*/
protected $permissions;
/**
* #var integer $company_id
*
* #ORM\Column(name="company_id", type="integer")
*/
protected $company_id;
/**
* #var integer $role_id
*
* #ORM\Column(name="role_id", type="integer")
*/
protected $role_id;
/**
* #ORM\OneToOne(targetEntity="Company")
* #ORM\JoinColumn( name="company_id", referencedColumnName="id" )
*/
protected $companies;
/**
* #ORM\OneToOne(targetEntity="UsersRole")
* #ORM\JoinColumn( name="role_id", referencedColumnName="id" )
*/
protected $listRoles;
public function __construct() {
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set password
*
* #param string $password
* #return Users
*/
public function setPassword($password)
{
$this->password = sha1($password);
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set username
*
* #param string $username
* #return Users
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set description
*
* #param string $description
* #return Users
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set permissions
*
* #param string $permissions
* #return Users
*/
public function setPermissions($permissions)
{
$this->permissions = $permissions;
return $this;
}
/**
* Get permissions
*
* #return string
*/
public function getPermissions()
{
return $this->permissions;
}
/**
* Set company_id
*
* #param Company $company_id
* #return Users
*/
public function setCompanyId($company_id)
{
$this->company_id = $company_id;
return $this;
}
/**
* Get company_id
*
* #return integer
*/
public function getCompanyId()
{
return $this->company_id;
}
public function equals(UserInterface $user) {
return $this->getUsername() == $user->getUsername();
}
public function eraseCredentials() {
}
/**
* Get roles
*
* #return String
*/
public function getRoles() {
$roles = $this->getListRoles();
return (array)$roles->getName();
}
/**
* Get roles
*
* #return \UsersRole
*/
public function getListRoles()
{
return $this->listRoles;
}
/**
* Set roles
*
* #param \UsersRole
* #return Users
*/
public function setListRoles($roles)
{
$this->listRoles = $roles;
return $this;
}
/**
* Set role_id
*
* #param integer
* #return Users
*/
public function setRoleID($roleId) {
$this->role_id = $roleId;
return $this;
}
public function getSalt() {
}
/**
* Get company
*
* #return Company
*/
public function getCompanies()
{
return $this->companies;
}
/**
* Set company
*
* #param Company $company
* #return Users
*/
public function setCompanies($company)
{
$this->companies = $company;
return $this;
}
}
UsersRole.php
<?php
namespace Trucking\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* USERS_ROLE
*
* #ORM\Table(name="USERS_ROLE")
* #ORM\Entity
*/
class UsersRole
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=30)
*/
protected $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=200)
*/
protected $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return USERS_ROLE
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return USERS_ROLE
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
The controller hasn't been changed
public function editAction($id) {
$user = $this->getDoctrine()
->getEntityManager()
->getRepository('TruckingMainBundle:Users')
->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find user id.');
}
$form = $this->createForm(new \Trucking\AdminBundle\Form\UserType(), $user);
$request = $this->getRequest();
//save data
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('tracking_admin_users'));
}
}
return $this->render('TruckingAdminBundle:user:edit.html.twig', array(
'id' => $id,
'form' => $form->createView()
)
);
}
UserType.php
<?php
namespace Trucking\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints;
class UserType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add("username","text",array(
"label" => "Name",
'attr' => array(
'class' => 'input-xlarge',
),
'constraints' => new Constraints\Length(array('min' => 3))
))
->add("password","password",array(
"label" => "Password",
'attr' => array(
'class' => 'input-xlarge',
),
'constraints' => new Constraints\Length(array('min' => 3))
))
->add("listRoles","entity",array(
'label' => 'Roles',
'class' => 'TruckingMainBundle:UsersRole' ,
'property' => 'name'
))
->add("companies","entity",array(
'label' => 'Companies',
'class' => 'TruckingMainBundle:Company' ,
'property' => 'name'
))
->add("description","text",array(
"label" => "Description",
'attr' => array(
'class' => 'input-xlarge'
),
'constraints' => new Constraints\NotBlank()
));
}
public function getName()
{
return 'trucking_adminbundle_usertype';
}
}

Categories