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';
}
}
Related
I'm currently trying to create a form so the user can add (multiple) business hours for a company.
The create form work just fine, but the edit form seems to keep throwing the this error.
Unable to transform value for property path "[open_time]": Expected a
\DateTimeInterface.
When I change the "open_time" inside my BusinessHoursType form type from TimeType to TextType. It seems to be working fine. But users will have to enter the data in a text field opposed to the hour/minutes dropdown.
I'm also checking if a specific company is open or not using the time and days entered.
How can I get this to work with TimeType?
I feel like I'm overlooking something small here.
Business Entity
class Business
{
use TimestampTrait;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, unique=true)
*
* #Assert\NotBlank()
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*
* #Assert\NotBlank()
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="website", type="string", length=255, nullable=true)
* #Assert\Url()
*/
private $website;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=255, nullable=true)
*
* #Assert\NotBlank()
* #Assert\Regex(
* pattern="/^((\+|00)32\s?|0)(\d\s?\d{3}|\d{2}\s?\d{2})(\s?\d{2}){2}$/",
* message="Gelieve een geldig telefoonnummer in te vullen"
* )
*/
//TODO: regex belgian mobile number (/^((\+|00)32\s?|0)4(60|[789]\d)(\s?\d{2}){3}$/)
private $phone;
/**
* #var bool
*
* #ORM\Column(name="open_24h", type="boolean", options={"default"=false})
*/
private $open24h;
/**
* #var array
*
* #ORM\Column(name="operation_hours", type="json_array")
*/
private $businessHours;
/**
* #var int
*
* #ORM\Column(name="page_views", type="integer", options={"default"=0})
*/
private $pageViews;
/**
* #var string
*
* #ORM\Column(name="google_places_place_id", type="string", length=255, nullable=true, unique=true)
*/
private $googlePlacesPlaceId;
/**
* #var string
*
* #ORM\Column(name="foursquare_venue_id", type="string", length=255, nullable=true, unique=true)
*/
private $foursquareVenueId;
// Member Variables for Relationships.
// -----------------------------------
/**
* Many Businesses have One Merchant.
* #ORM\ManyToOne(targetEntity="Merchant", inversedBy="businesses")
* #ORM\JoinColumn(name="merchant_id", referencedColumnName="id")
*/
private $merchant;
/**
* One Business has One Address.
* #ORM\OneToOne(targetEntity="Address", mappedBy="business")
* #ORM\JoinColumn(name="address_id", referencedColumnName="id")
*
* #Assert\Valid()
*/
private $address;
/**
* One Business has many Review.
* #ORM\OneToMany(targetEntity="Review", mappedBy="business")
*/
private $reviews;
/**
* Many Businesses have One Business Type.
* #ORM\ManyToOne(targetEntity="BusinessType", inversedBy="businesses")
* #ORM\JoinColumn(name="businessType_id", referencedColumnName="id")
*/
private $businessType;
/**
* One Business has Many Images.
* #ORM\OneToMany(targetEntity="Image", mappedBy="business")
*/
private $images;
/**
* One Business has Many Promotions.
* #ORM\OneToMany(targetEntity="Promotion", mappedBy="business")
*/
private $promotions;
/**
* One Business has Many Prdocuts.
* #ORM\OneToMany(targetEntity="Product", mappedBy="business")
*/
private $products;
/**
* Business constructor.
*/
public function __construct()
{
$this->setCreatedAt(new DateTime());
$this->setUpdatedAt(new DateTime());
$this->setPageViews(0);
$this->setReviews(new ArrayCollection());
$this->setImages(new ArrayCollection());
$this->setPromotions(new ArrayCollection());
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Business
*/
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 Business
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set website
*
* #param string $website
*
* #return Business
*/
public function setWebsite($website)
{
$this->website = $website;
return $this;
}
/**
* Get website
*
* #return string
*/
public function getWebsite()
{
return $this->website;
}
/**
* Set phone
*
* #param string $phone
*
* #return Business
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set open24h
*
* #param boolean $open24h
*
* #return Business
*/
public function setOpen24h($open24h)
{
$this->open24h = $open24h;
return $this;
}
/**
* Get open24h
*
* #return bool
*/
public function getOpen24h()
{
return $this->open24h;
}
/**
* #return array
*/
public function getBusinessHours(): ?array
{
return $this->businessHours;
}
/**
* #param array $businessHours
*/
public function setBusinessHours(array $businessHours)
{
$this->businessHours = $businessHours;
}
public function addBusinessHours(array $businessHours)
{
$this->businessHours->add($businessHours);
}
public function removeBusinessHours(array $businessHours)
{
$this->businessHours->removeElement($businessHours);
}
/**
* Set pageViews
*
* #param integer $pageViews
*
* #return Business
*/
public function setPageViews($pageViews)
{
$this->pageViews = $pageViews;
return $this;
}
/**
* Get pageViews
*
* #return int
*/
public function getPageViews()
{
return $this->pageViews;
}
/**
* Set googlePlacesPlaceId
*
* #param string $googlePlacesPlaceId
*
* #return Business
*/
public function setGooglePlacesPlaceId($googlePlacesPlaceId)
{
$this->googlePlacesPlaceId = $googlePlacesPlaceId;
return $this;
}
/**
* Get googlePlacesPlaceId
*
* #return string
*/
public function getGooglePlacesPlaceId()
{
return $this->googlePlacesPlaceId;
}
/**
* Set foursquareVenueId
*
* #param string $foursquareVenueId
*
* #return Business
*/
public function setFoursquareVenueId($foursquareVenueId)
{
$this->foursquareVenueId = $foursquareVenueId;
return $this;
}
/**
* Get foursquareVenueId
*
* #return string
*/
public function getFoursquareVenueId()
{
return $this->foursquareVenueId;
}
// Member Methods for Relationships.
// ---------------------------------
/**
* Set Merchant
*
* #param Merchant $merchant
*
* #return Business
*/
public function setMerchant(Merchant $merchant)
{
$this->merchant = $merchant;
return $this;
}
/**
* Get Merchant
*
* #return Merchant
*/
public function getMerchant()
{
return $this->merchant;
}
/**
* Set Address
*
* #param Address $address
*
* #return Business
*/
public function setAddress(Address $address)
{
$this->address = $address;
return $this;
}
/**
* Get Address
*
* #return Address
*/
public function getAddress()
{
return $this->address;
}
/**
* Get Reviews.
*
* #return ArrayCollection
*/
public function getReviews()
{
return $this->reviews;
}
/**
* Set Reviews.
*
* #param ArrayCollection $reviews
*
* #return Business
*/
public function setReviews(ArrayCollection $reviews)
{
$this->reviews = $reviews;
return $this;
}
/**
* Add review.
*
* #param Review $review
*
* #return Business
*/
public function addReview(Review $review)
{
$this->reviews[] = $review;
return $this;
}
/**
* Get Business Type.
*
* #return BusinessType
*/
public function getBusinessType()
{
return $this->businessType;
}
/**
* Set Business Type.
*
* #param BusinessType $businessType
*
* #return Business
*/
public function setBusinessType(BusinessType $businessType)
{
$this->businessType = $businessType;
return $this;
}
/**
* Get Images.
*
* #return ArrayCollection
*/
public function getImages()
{
return $this->images;
}
/**
* Set Images.
*
* #param ArrayCollection $images
*
* #return Business
*/
public function setImages(ArrayCollection $images)
{
$this->images = $images;
return $this;
}
/**
* Add image
*
* #param Image $image
*
* #return $this
*/
public function addImage(Image $image)
{
$this->images[] = $image;
return $this;
}
/**
* Get Promotions.
*
* #return ArrayCollection
*/
public function getPromotions()
{
return $this->promotions;
}
/**
* Set Promotions.
*
* #param ArrayCollection $promotions
*
* #return Business
*/
public function setPromotions(ArrayCollection $promotions)
{
$this->promotions = $promotions;
return $this;
}
/**
* Add Promotion
*
* #param Promotion $promotion
*
* #return $this
*/
public function addPromotion(Promotion $promotion)
{
$this->promotions[] = $promotion;
return $this;
}
/**
* Get Products
* #return Product
*/
public function getProducts()
{
return $this->products;
}
/**
* Set Product
*
* #param Product $products
*/
public function setProducts(Product $products)
{
$this->products = $products;
}
public function addProduct(Product $product)
{
$this->products[] = $product;
return $this;
}
/**
* Check if the business is open
*/
public function isOpen()
{
$curDate = new DateTime();
$curDay = (int)$curDate->format('N');
$curTime = $curDate->format('H:i:s');
$businessHours = $this->getBusinessHours();
$isOpen = $this->getOpen24h();
if (!$this->getOpen24h()) {
foreach ($businessHours as $hoursSet) {
$openTime = date('H:i:s', strtotime($hoursSet['open_time']['date']));
$closeTime = date('H:i:s', strtotime($hoursSet['close_time']['date']));
if (in_array($curDay, $hoursSet["day"]) && $curTime >= $openTime && $curTime <= $closeTime) {
$isOpen = true;
};
}
}
return $isOpen;
}
public function __toString()
{
return $this->getName();
}
}
BusinessController
public function editAction(Request $request, Business $business)
{
$deleteForm = $this->createDeleteForm($business);
//createForm seems to be giving me the error.
$editForm = $this->createForm('AppBundle\Form\BusinessType', $business);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
//TODO: translations
$this->addFlash(
'success',
'Saved Changes'
);
return $this->redirectToRoute('business_edit', ['id' => $business->getId()]);
}
return $this->render('business/edit.html.twig',
[
'business' => $business,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
]
);
}
BusinessType
$builder->add('businessHours',
CollectionType::class,
[
'entry_type' => BusinessHoursType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
]
);
BusinessHoursType
class BusinessHoursType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('day',
ChoiceType::class,
[
'label' => 'label.day',
'translation_domain' => 'base',
'choices' => array_flip(DateConstants::DAYS),
'expanded' => true,
'multiple' => true,
]
);
$builder->add('open_time',
TimeType::class,
[
'label' => 'label.open_time',
'translation_domain' => 'business',
'input' => 'datetime',
'minutes' => [
0,
15,
30,
45,
],
'attr' => [
'class' => 'time-selector',
],
]
);
$builder->add('close_time',
TimeType::class,
[
'label' => 'label.close_time',
'translation_domain' => 'business',
'input' => 'datetime',
'minutes' => [
0,
15,
30,
45,
],
'attr' => [
'class' => 'time-selector',
],
]
);
}
}
Everything get saved in my database as 1 property named business_hours as follows:
[{"day":[1,3],"open_time":{"date":"1970-01-01 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Brussels"},"close_time":{"date":"1970-01-01 21:00:00.000000","timezone_type":3,"timezone":"Europe\/Brussels"}}]
My newAction is as follows (which works and saved everything in the database including the business hours
public function newAction(Request $request)
{
$business = new Business();
$form = $this->createForm(BusinessType::class, $business);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$address = $form->get('address')->getData();
$business->setAddress($address);
$em = $this->getDoctrine()->getManager();
$em->persist($address);
$em->persist($business);
$em->flush();
$this->addFlash(
'success',
$this->get('translator')->trans('business.message.created')
);
return $this->redirectToRoute('business_show', ['id' => $business->getId()]);
}
return $this->render('business/new.html.twig',
[
'business' => $business,
'form' => $form->createView(),
]
);
}
I am trying to create a little CRUD system with 2 entities and a OneToMany relationship between these 2 entities.
My entities are Location & Job. I created the entities and created the crud controller via doctrine for both.
Location CRUD works great but Job only Read & Delete works. When I try to create a new Job it throws the following exception:
Catchable Fatal Error: Object of class DataBundle\Entity\Location
could not be converted to string
I have no idea what it means or what is causing it.
If anyone could help me out that would be realy awesome!
Many thanks in advance!
Here is my code.
Entities:
Location
<?php
namespace DataBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Location
*
* #ORM\Table(name="location")
* #ORM\Entity(repositoryClass="DataBundle\Repository\LocationRepository")
*/
class Location
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="street", type="string", length=255)
*/
private $street;
/**
* #var string
*
* #ORM\Column(name="number", type="string", length=25)
*/
private $number;
/**
* #var string
*
* #ORM\Column(name="postalcode", type="string", length=4)
*/
private $postalcode;
/**
* #var string
*
* #ORM\Column(name="city", type="string", length=255)
*/
private $city;
/**
* #var Job[] Available jobs for this location.
*
* #ORM\OneToMany(targetEntity="Job", mappedBy="location")
*/
private $jobs;
public function __construct()
{
$this->jobs = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Location
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set street
*
* #param string $street
*
* #return Location
*/
public function setStreet($street)
{
$this->street = $street;
return $this;
}
/**
* Get street
*
* #return string
*/
public function getStreet()
{
return $this->street;
}
/**
* Set number
*
* #param string $number
*
* #return Location
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* Get number
*
* #return string
*/
public function getNumber()
{
return $this->number;
}
/**
* Set postalcode
*
* #param string $postalcode
*
* #return Location
*/
public function setPostalcode($postalcode)
{
$this->postalcode = $postalcode;
return $this;
}
/**
* Get postalcode
*
* #return string
*/
public function getPostalcode()
{
return $this->postalcode;
}
/**
* Set city
*
* #param string $city
*
* #return Location
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* #return string
*/
public function getCity()
{
return $this->city;
}
/**
* Add job
*
* #param \DataBundle\Entity\Job $job
*
* #return Location
*/
public function addJob(\DataBundle\Entity\Job $job)
{
$this->jobs[] = $job;
return $this;
}
/**
* Remove job
*
* #param \DataBundle\Entity\Job $job
*/
public function removeJob(\DataBundle\Entity\Job $job)
{
$this->jobs->removeElement($job);
}
/**
* Get jobs
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getJobs()
{
return $this->jobs;
}
}
Job:
<?php
namespace DataBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Job
*
* #ORM\Table(name="job")
* #ORM\Entity(repositoryClass="DataBundle\Repository\JobRepository")
*/
class Job
{
/**
* #var int
*
* #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;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #var Location
*
* #ORM\ManyToOne(targetEntity="Location", inversedBy="jobs")
* #ORM\JoinColumn(name="location_id", referencedColumnName="id")
*/
private $location;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Job
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
*
* #return Job
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set location
*
* #param \DataBundle\Entity\Location $location
*
* #return Job
*/
public function setLocation(\DataBundle\Entity\Location $location = null)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return \DataBundle\Entity\Location
*/
public function getLocation()
{
return $this->location;
}
}
My new action in the JobController:
/**
* Creates a new job entity.
*
*/
public function newAction(Request $request)
{
$job = new Job();
$form = $this->createForm('DataBundle\Form\JobType', $job);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($job);
$em->flush($job);
return $this->redirectToRoute('job_show', array('id' => $job->getId()));
}
return $this->render('job/new.html.twig', array(
'job' => $job,
'form' => $form->createView(),
));
}
DataBundle/Form/JobTypep
<?php
namespace DataBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class JobType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title')->add('description')->add('location') ;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'DataBundle\Entity\Job'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'databundle_job';
}
}
You can't use location as text field in your form, location is object.
You can fix this error by using form data transformers that will convert location into text on form output and text in location object on form submit.
http://symfony.com/doc/current/form/data_transformers.html
Or by using form type EnityType for location:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title')->add('description');
$builder
->add('location', Symfony\Bridge\Doctrine\Form\Type\EntityType::class, [
'required' => false,
'expanded' => false,
'multiple' => false,
'class' => 'DataBundle\\Entity\\Location',
'empty_data' => '',
'choice_label' => 'name',
'label' => 'Location',
]);
}
http://symfony.com/doc/current/reference/forms/types/entity.html
I have symfony form with choice field. I want to load choices from my entity class static method. can i use data or CallbackChoiceLoader? what is the best practise?
this is my field:
class CarType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, [
// This choices I would like to load from:
// 'choices' => $car::getTypes(),
'choices' => [
'Critical' => 'critical',
'Medium' => 'medium',
'Info' => 'info',
],
'label' => 'Type'
])
->add('name', TextType::class, [
'label' => 'Name'
])
->add('save', SubmitType::class, [
'label' => 'Save'
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Car'
]);
}
public function getName()
{
return 'car';
}
}
This is my entity:
/**
* #ORM\Entity
* #ORM\Table(name="car")
*/
class Car
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $type
*
* #Assert\NotBlank()
* #ORM\Column(name="type")
*/
private $type;
/**
* #var string $name
*
* #Assert\NotBlank()
* #ORM\Column(name="name")
*/
private $name;
/**
* #var \DateTime $created
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
private static $types = ['main', 'custom'];
public function __construct()
{
$this->created = new \DateTime('now', new \DateTimeZone('Europe/Ljubljana'));
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get types
*
* #return array
*/
public function getTypes()
{
return self::$types;
}
/**
* Set type
*
* #param string $type
*
* #return Car
*/
public function setType($type)
{
if (in_array($type, $this->getTypes())) {
$this->type = $type;
}
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set name
*
* #param string $name
*
* #return Car
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return Car
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
How and what can i use to load choices from $car::getTypes() method like i commented in form so that the choices are loaded dynamicly based on values in getTypes entity method?
Edit: This is option 1. Option 2 below more directly answers the question.
The preferred method of creating a choice form field from an entity is to use the EntityType field. Here is an example from an application that requires an ethnicity field. Below that is the Ethnicity entity.
form field:
->add('ethnicity', EntityType::class, array(
'label' => 'Ethnicity:',
'class' => 'AppBundle:Ethnicity',
'choice_label' => 'abbreviation',
'expanded' => false,
'placeholder' => 'Select ethnicity',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('e')
->orderBy('e.abbreviation', 'ASC')
;
},
))
Ethnicity entity:
/**
* Ethnicity.
*
* #ORM\Table(name="ethnicity")
* #ORM\Entity
*/
class Ethnicity
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="ethnicity", type="string", length=45, nullable=true)
*/
protected $ethnicity;
/**
* #var string
*
* #ORM\Column(name="abbr", type="string", length=45, nullable=true)
*/
protected $abbreviation;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Member", mappedBy="ethnicity", cascade={"persist"})
*/
protected $members;
/**
* Constructor.
*/
public function __construct()
{
$this->members = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set ethnicity.
*
* #param string $ethnicity
*
* #return Ethnicity
*/
public function setEthnicity($ethnicity)
{
$this->ethnicity = $ethnicity;
return $this;
}
/**
* Get ethnicity.
*
* #return string
*/
public function getEthnicity()
{
return $this->ethnicity;
}
/**
* Set abbreviation.
*
* #param string $abbreviation
*
* #return Ethnicity
*/
public function setAbbreviation($abbreviation)
{
$this->abbreviation = $abbreviation;
return $this;
}
/**
* Get abbreviation.
*
* #return string
*/
public function getAbbreviation()
{
return $this->abbreviation;
}
/**
* Add members.
*
* #param \AppBundle\Entity\Member $members
*
* #return Ethnicity
*/
public function addMember(\AppBundle\Entity\Member $members)
{
$this->members[] = $members;
return $this;
}
/**
* Remove members.
*
* #param \AppBundle\Entity\Member $members
*/
public function removeMember(\Truckee\ProjectmanaBundle\Entity\Member $members)
{
$this->members->removeElement($members);
}
/**
* Get members.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMembers()
{
return $this->members;
}
/**
* #var bool
*
* #ORM\Column(name="enabled", type="boolean", nullable=true)
*/
protected $enabled;
/**
* Set enabled.
*
* #param bool $enabled
*
* #return enabled
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled.
*
* #return bool
*/
public function getEnabled()
{
return $this->enabled;
}
}
Option 2:
If you really want to do that, then here's an approach:
Modify your static property $types such that the choices are values in an array, e.g., $types = array(1 => 'main', 2 => 'custom')
In your controller, add a use statement for the Car entity.
In controller action:
$car = new Car();
$types = $car->getTypes;
Use the answer to Passing data to buildForm() in Symfony 2.8/3.0 to see how to pass $types to your form.
I have two entities Store and Category and each Store has it's own categories.
I'd like that when a Store owner's try to add a new category and category_parent, just the categories related to current Store will be displayed.
Right now, all categories are displayed in the select-option.
I'm using Tree Gedmo extension to manage Category entity and I use getChildrenQueryBuilder method to select categories.
How can I modify this method and add my specific constraint ?
$store which is the constraint is declared in the controller action down.
I'd like te set current Category option disabled when he try to add a category_parent, so category and category parent must be differnt.
I hope it's clear
CategoryType.php
<?php
namespace Project\StoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
class CategoryType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//..........
//..........
->add('category', 'entity', array(
'required' => false,
'label' => 'Category parent',
'class' => 'ProjectStoreBundle:Category',
'attr' => array('class' => 'col-sm-8'),
'empty_value' => 'Select one category',
'property' => 'indentedName',
'multiple' => false,
'expanded' => false ,
'query_builder' => function (\Project\StoreBundle\Entity\CategoryRepository $r)
{
return $r->getChildrenQueryBuilder(null, null, 'root', 'asc', false);
}
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\StoreBundle\Entity\Category'
));
}
/**
* #return string
*/
public function getName()
{
return 'project_storebundle_category';
}
}
Entity/Category.php
<?php
namespace Project\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Category
* #Gedmo\Tree(type="nested")
* #ORM\Table()
* #ORM\Entity(repositoryClass="Project\StoreBundle\Entity\CategoryRepository")
* #ORM\HasLifeCycleCallbacks()
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*
*#Assert\NotBlank(message="Please enter the name of categorie.")
*/
private $name;
/**
* #Gedmo\slug(fields={"name"}, unique_base="uniqueBase")
* #ORM\Column(name="slug",length=255, unique=false)
*/
private $slug ;
/**
* #ORM\Column(name="uniqueBase", type="integer")
*/
private $uniqueBase ;
/**
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #ORM\Column(name="metaDescription", type="string", length=255, nullable=true)
*
* #Assert\Length(
* max=255,
* maxMessage="message"
* )
*/
private $metaDescription;
/**
* #ORM\Column(name="metaKeywords", type="string", length=255, nullable=true)
*
* #Assert\Length(
* max=255,
* maxMessage="message"
* )
*/
private $metaKeywords;
/**
* #ORM\Column(name="enabled", type="boolean", nullable=false)
*/
private $enabled;
/**
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\Column(name="root", type="integer", nullable=true)
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
/**
*non mapped property
*/
private $indentedName;
/**
*non mapped property
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="Project\StoreBundle\Entity\Store", inversedBy="categories", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $store ;
/**
* Constructor
*/
public function __construct()
{
$this->children = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set slug
*
* #param string $slug
* #return Category
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set uniqueBase
*
* #param integer $uniqueBase
* #return Category
*/
public function setUniqueBase($uniqueBase)
{
$this->uniqueBase = $uniqueBase;
return $this;
}
/**
* Get uniqueBase
*
* #return integer
*/
public function getUniqueBase()
{
return $this->uniqueBase;
}
/**
* Set description
*
* #param string $description
* #return Category
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set metaDescription
*
* #param string $metaDescription
* #return Category
*/
public function setMetaDescription($metaDescription)
{
$this->metaDescription = $metaDescription;
return $this;
}
/**
* Get metaDescription
*
* #return string
*/
public function getMetaDescription()
{
return $this->metaDescription;
}
/**
* Set metaKeywords
*
* #param string $metaKeywords
* #return Category
*/
public function setMetaKeywords($metaKeywords)
{
$this->metaKeywords = $metaKeywords;
return $this;
}
/**
* Get metaKeywords
*
* #return string
*/
public function getMetaKeywords()
{
return $this->metaKeywords;
}
/**
* Set enabled
*
* #param boolean $enabled
* #return Category
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* #return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set parent
*
* #param \Project\StoreBundle\Entity\Category $parent
* #return Category
*/
public function setParent(\Project\StoreBundle\Entity\Category $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return \Project\StoreBundle\Entity\Category
*/
public function getParent()
{
return $this->parent;
}
/**
* Set lft
*
* #param integer $lft
* #return Category
*/
public function setLft($lft)
{
$this->lft = $lft;
return $this;
}
/**
* Get lft
*
* #return integer
*/
public function getLft()
{
return $this->lft;
}
/**
* Set lvl
*
* #param integer $lvl
* #return Category
*/
public function setLvl($lvl)
{
$this->lvl = $lvl;
return $this;
}
/**
* Get lvl
*
* #return integer
*/
public function getLvl()
{
return $this->lvl;
}
/**
* Set rgt
*
* #param integer $rgt
* #return Category
*/
public function setRgt($rgt)
{
$this->rgt = $rgt;
return $this;
}
/**
* Get rgt
*
* #return integer
*/
public function getRgt()
{
return $this->rgt;
}
/**
* Set root
*
* #param integer $root
* #return Category
*/
public function setRoot($root)
{
$this->root = $root;
return $this;
}
/**
* Get root
*
* #return integer
*/
public function getRoot()
{
return $this->root;
}
/**
* Add children
*
* #param \Project\StoreBundle\Entity\Category $children
* #return Category
*/
public function addChild(\Project\StoreBundle\Entity\Category $children)
{
$this->children[] = $children;
return $this;
}
/**
* Remove children
*
* #param \Project\StoreBundle\Entity\Category $children
*/
public function removeChild(\Project\StoreBundle\Entity\Category $children)
{
$this->children->removeElement($children);
}
/**
* Get children
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Get IndentedName
*
*/
public function getIndentedName()
{
return str_repeat("-----", $this->lvl).$this->name;
}
/**
* Get category
*
*/
public function getCategory()
{
return $this->category;
}
/**
* Set store
*
* #param \Project\StoreBundle\Entity\Store $store
* #return Category
*/
public function setStore(\Project\StoreBundle\Entity\Store $store = null)
{
$this->store = $store;
return $this;
}
/**
* Get store
*
* #return \Project\StoreBundle\Entity\Store
*/
public function getStore()
{
return $this->store;
}
}
Controller
/**
* Create a new Category entity.
*
*/
/**
* #ParamConverter("store", options={"mapping": {"store_id":"id"}})
*/
public function newAction(Store $store)
{
// keep in mind, this will call all registered security voters
if (false === $this->get('security.context')->isGranted('edit', $store)) {
throw new AccessDeniedException('Unauthorised access!');
}
$category = new Category();
$category->setStore($store);
$category->setUniqueBase($store->getId());
$form = $this->createForm(new CategoryType(), $category);
$request = $this->getRequest();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->flush();
$this->get('session')->getFlashBag()->add('message', 'Category enregistred');
return $this->redirect( $this->generateUrl('dashboard_category_index', array('store_id' => $store->getId())));
}
}
return $this->render('ProjectDashboardBundle:Category:new.html.twig',
array(
'form' => $form->createView() ,
'store' =>$store,
));
}
I managed to pass the parameter $store to the form, but I don't know how to use it as a constraint in getChildrenQueryBuilder method.
Should I create a new custom method? I prefer to use getChildrenQueryBuilder if it is possible.
Here is the new code
CategoryType.php
class CategoryType extends AbstractType
{
private $store;
public function __construct($store)
{
$this->store = $store;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$store = $this->store;
$builder
//...........
//...........
->add('parent', 'entity', array(
'required' => false,
'label' => 'Category parent',
'class' => 'ProjectStoreBundle:Category',
'attr' => array('class' => 'col-sm-8'),
'empty_value' => 'Select one category',
'property' => 'indentedName',
'multiple' => false,
'expanded' => false ,
'query_builder' => function (\Project\StoreBundle\Entity\CategoryRepository $r) use ($store)
{
return $r->getChildrenQueryBuilder(null, null, 'root', 'asc', false);
}
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\StoreBundle\Entity\Category'
));
}
/**
* #return string
*/
public function getName()
{
return 'project_storebundle_category';
}
}
Controller
/**
* #ParamConverter("store", options={"mapping": {"store_id":"id"}})
*/
public function newAction(Store $store)
{
// keep in mind, this will call all registered security voters
if (false === $this->get('security.context')->isGranted('edit', $store)) {
throw new AccessDeniedException('Unauthorised access!');
}
$category = new Category();
$category->setStore($store);
$category->setUniqueBase($store->getId());
$form = $this->createForm(new CategoryType($store), $category);
$request = $this->getRequest();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->flush();
$this->get('session')->getFlashBag()->add('message', 'Category enregistred');
return $this->redirect( $this->generateUrl('dashboard_category_index', array('store_id' => $store->getId())));
}
}
return $this->render('ProjectDashboardBundle:Category:new.html.twig',
array(
'form' => $form->createView() ,
'store' =>$store,
));
}
You're not saying which Symfony2 version you're using, but generically speaking, you just need to find a way to pass the current store to your form builder and use it in the method that filters the possible categories.
Take a look at this one, or this one, basically you just need to inject the $store into your form builder, and then you (almost) have it :-)
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