Doctrine ODM EmbedOne to EmbedMany - mongodb

I use Mongodb with Doctrine2 to log actions on appointments fot stats purpose. I had to modify the Entity from
class Appointment {
/** #ODM\Id */
protected $id;
/** #ODM\EmbedOne(targetDocument="Product") */
private $product;
to
class Appointment {
/** #ODM\Id */
protected $id;
/** #ODM\EmbedMany(targetDocument="Product") */
private $products;
So earlier one appointment had one product, but now one appointment may have multiple products. Every things work fine while saving.
My question is how do I update the old documents 'product' to put them also into an array?
Regards Andrea

You can use the migration features described here: http://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/migrating-schemas.html
In your case, you can update your Doctrine document this way:
<?php
class Appointment
{
/**
* ODM\EmbedOne(targetDocument="Product")
* #ODM\NotSaved
*/
protected $product;
/**
* #ODM\EmbedMany(targetDocument="Product")
*/
protected $products;
/**
* #ODM\AlsoLoad({"product"})
*/
public function populateProducts($product)
{
$this->products = [$product];
$this->product = null;
}
/**
* #ODM\AlsoLoad({"product"})
*/
public function populateProducts($product)
{
$this->products = [$product];
}
}
This way, the old single product is cast to a collection of products.

<?php
namespace Application\Entity\Documents;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* #ODM\Document(collection="appointment")
*/
class Appointment {
/** #ODM\Id */
protected $id;
/** #ODM\String #ODM\Index */
protected $department;
/** #ODM\String #ODM\Index */
protected $action;
/** #ODM\Int #ODM\Index */
protected $idAppointment;
/** #ODM\String */
protected $service_order;
/** #ODM\Int */
protected $sales_order;
/** #ODM\String */
protected $access_number;
/** #ODM\String */
protected $so_type;
/** #ODM\String */
protected $stage;
/** #ODM\String */
protected $se_items;
/** #ODM\String #ODM\Index */
protected $id_va;
/** #ODM\String */
protected $id_icms;
/** #ODM\String */
protected $company;
/** #ODM\String */
protected $customer_name;
/** #ODM\String */
protected $street;
/** #ODM\String */
protected $housenumber;
/** #ODM\String */
protected $building;
/** #ODM\String */
protected $appartment;
/** #ODM\String */
protected $postal_code;
/** #ODM\String */
protected $city;
/** #ODM\String */
protected $email;
/** #ODM\String */
protected $contact_number;
/** #ODM\String */
protected $ref_isp;
/** #ODM\String */
protected $comment;
/** #ODM\Date */
protected $first_available_schedule;
/** #ODM\Date */
protected $request_cancellation;
/** #ODM\Boolean */
protected $asap;
/** #ODM\String */
protected $allday;
/** #ODM\String #ODM\Index */
protected $operator;
/** #ODM\String */
protected $createdBy;
/** #ODM\String */
protected $movedBy;
/** #ODM\String */
protected $network;
/** #ODM\Date #ODM\Index */
private $created;
/** #ODM\Date #ODM\Index */
private $posted;
/** #ODM\String */
protected $actionBy;
/** #ODM\EmbedOne(targetDocument="Schedule") */
private $schedule;
/**
* #ODM\EmbedOne(targetDocument="Product")
* #ODM\NotSaved
*/
protected $product;
/** #ODM\EmbedMany(targetDocument="Product") */
private $products = array();
/**
* #ODM\AlsoLoad({"product"})
*/
public function populateProducts($product) {
$this->products = [$product];
$this->product = null;
}
/** #ODM\String */
protected $mqMsg;
public function __construct() {
$this->products = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId() {
return $this->id;
}
public function getDepartment() {
return $this->department;
}
public function getAction() {
return $this->action;
}
public function getIdAppointment() {
return $this->idAppointment;
}
public function getService_order() {
return $this->service_order;
}
public function getSales_order() {
return $this->sales_order;
}
public function getAccess_number() {
return $this->access_number;
}
public function getSo_type() {
return $this->so_type;
}
public function getStage() {
return $this->stage;
}
public function getSe_items() {
return $this->se_items;
}
public function getId_va() {
return $this->id_va;
}
public function getId_icms() {
return $this->id_icms;
}
public function getCompany() {
return $this->company;
}
public function getCustomer_name() {
return $this->customer_name;
}
public function getStreet() {
return $this->street;
}
public function getHousenumber() {
return $this->housenumber;
}
public function getBuilding() {
return $this->building;
}
public function getAppartment() {
return $this->appartment;
}
public function getPostal_code() {
return $this->postal_code;
}
public function getCity() {
return $this->city;
}
public function getEmail() {
return $this->email;
}
public function getContact_number() {
return $this->contact_number;
}
public function getRef_isp() {
return $this->ref_isp;
}
public function getComment() {
return $this->comment;
}
public function getFirst_available_schedule() {
return $this->first_available_schedule;
}
public function getRequest_cancellation() {
return $this->request_cancellation;
}
public function getAsap() {
return $this->asap;
}
public function getAllday() {
return $this->allday;
}
public function getOperator() {
return $this->operator;
}
public function getCreatedBy() {
return $this->createdBy;
}
public function getMovedBy() {
return $this->movedBy;
}
public function getNetwork() {
return $this->network;
}
public function getCreated() {
return $this->created;
}
public function getPosted() {
return $this->posted;
}
public function getActionBy() {
return $this->actionBy;
}
public function getSchedule() {
return $this->schedule;
}
public function getProduct() {
return $this->product;
}
public function getProducts() {
return $this->products;
}
public function getMqMsg() {
return $this->mqMsg;
}
public function setId($id) {
$this->id = $id;
}
public function setDepartment($department) {
$this->department = $department;
}
public function setAction($action) {
$this->action = $action;
}
public function setIdAppointment($idAppointment) {
$this->idAppointment = $idAppointment;
}
public function setService_order($service_order) {
$this->service_order = $service_order;
}
public function setSales_order($sales_order) {
$this->sales_order = $sales_order;
}
public function setAccess_number($access_number) {
$this->access_number = $access_number;
}
public function setSo_type($so_type) {
$this->so_type = $so_type;
}
public function setStage($stage) {
$this->stage = $stage;
}
public function setSe_items($se_items) {
$this->se_items = $se_items;
}
public function setId_va($id_va) {
$this->id_va = $id_va;
}
public function setId_icms($id_icms) {
$this->id_icms = $id_icms;
}
public function setCompany($company) {
$this->company = $company;
}
public function setCustomer_name($customer_name) {
$this->customer_name = $customer_name;
}
public function setStreet($street) {
$this->street = $street;
}
public function setHousenumber($housenumber) {
$this->housenumber = $housenumber;
}
public function setBuilding($building) {
$this->building = $building;
}
public function setAppartment($appartment) {
$this->appartment = $appartment;
}
public function setPostal_code($postal_code) {
$this->postal_code = $postal_code;
}
public function setCity($city) {
$this->city = $city;
}
public function setEmail($email) {
$this->email = $email;
}
public function setContact_number($contact_number) {
$this->contact_number = $contact_number;
}
public function setRef_isp($ref_isp) {
$this->ref_isp = $ref_isp;
}
public function setComment($comment) {
$this->comment = $comment;
}
public function setFirst_available_schedule($first_available_schedule) {
$this->first_available_schedule = $first_available_schedule;
}
public function setRequest_cancellation($request_cancellation) {
$this->request_cancellation = $request_cancellation;
}
public function setAsap($asap) {
$this->asap = $asap;
}
public function setAllday($allday) {
$this->allday = $allday;
}
public function setOperator($operator) {
$this->operator = $operator;
}
public function setCreatedBy($createdBy) {
$this->createdBy = $createdBy;
}
public function setMovedBy($movedBy) {
$this->movedBy = $movedBy;
}
public function setNetwork($network) {
$this->network = $network;
}
public function setCreated($created) {
$this->created = $created;
}
public function setPosted($posted) {
$this->posted = $posted;
}
public function setActionBy($actionBy) {
$this->actionBy = $actionBy;
}
public function setSchedule($schedule) {
$this->schedule = $schedule;
}
public function setProduct($product) {
$this->product = $product;
}
public function setProducts($products) {
$this->products = $products;
}
public function setMqMsg($mqMsg) {
$this->mqMsg = $mqMsg;
}
public function addProduct($product) {
$this->products[] = $product;
}
}
/** #ODM\EmbeddedDocument */
class Schedule {
/** #ODM\Id */
protected $id;
/** #ODM\String */
protected $layer;
/** #ODM\String */
protected $team;
/** #ODM\String */
protected $disponibility;
/** #ODM\Date #ODM\Index */
protected $duedate;
/** #ODM\Date #ODM\Index */
protected $dueperiod;
/** #ODM\Boolean */
protected $is_task;
function getId() {
return $this->id;
}
function getLayer() {
return $this->layer;
}
function getTeam() {
return $this->team;
}
function getDisponibility() {
return $this->disponibility;
}
function getDuedate() {
return $this->duedate;
}
function getDueperiod() {
return $this->dueperiod;
}
function getIs_task() {
return $this->is_task;
}
function setId($id) {
$this->id = $id;
}
function setLayer($layer) {
$this->layer = $layer;
}
function setTeam($team) {
$this->team = $team;
}
function setDisponibility($disponibility) {
$this->disponibility = $disponibility;
}
function setDuedate($duedate) {
$this->duedate = $duedate;
}
function setDueperiod($dueperiod) {
$this->dueperiod = $dueperiod;
}
function setIs_task($is_task) {
$this->is_task = $is_task;
}
}
/** #ODM\EmbeddedDocument */
class Product {
/** #ODM\Id */
protected $id;
/** #ODM\String */
protected $category;
/** #ODM\String */
protected $disponibility;
/** #ODM\String */
protected $abbr;
/** #ODM\Float */
protected $freeze_day;
/** #ODM\Boolean */
protected $regulated;
/** #ODM\Int */
protected $sla;
function getId() {
return $this->id;
}
function getCategory() {
return $this->category;
}
function getDisponibility() {
return $this->disponibility;
}
function getAbbr() {
return $this->abbr;
}
function getFreeze_day() {
return $this->freeze_day;
}
function getSenumber() {
return $this->senumber;
}
function getRegulated() {
return $this->regulated;
}
public function getSla() {
return $this->sla;
}
function setId($id) {
$this->id = $id;
}
function setCategory($category) {
$this->category = $category;
}
function setDisponibility($disponibility) {
$this->disponibility = $disponibility;
}
function setAbbr($abbr) {
$this->abbr = $abbr;
}
function setFreeze_day($freeze_day) {
$this->freeze_day = $freeze_day;
}
function setSenumber($senumber) {
$this->senumber = $senumber;
}
function setRegulated($regulated) {
$this->regulated = $regulated;
}
public function setSla($sla) {
$this->sla = $sla;
}
}

Related

How to return entity object type from EntityType class in form?

Every time I try to send data from form and use doctrine manager I have an error:
As you can see, this problem is according to user_type. I have another entity UserType in which I have this attribute and I want to use it in register form.
I have controller and I want to add all form input into database and then error occurs.
I would like to point out that I don't want to get and set each attribute manually via for instance:
$name = $form['name']->getData();
$userDetails->setName($name);
Because I think that by using entity manager it is supposed to do automatically like this:
UserController.php:
public function register(Request $request){
$user = new User();
$userType = new UserType();
$userDetails = new UserDetails();
$form = $this->createForm(RegisterFormType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted()){
$userDetails = $form->getData();
$em=$this->getDoctrine()->getManager();
$em->persist($userDetails);
$em->flush();
dd($form->getData());
My form in RegisterFormType.php:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
-> add('name',TextType::class,[
'data_class' => UserDetails::class,
'attr' => [
"placeholder" => 'Name'
],
])
-> add('surname',TextType::class,[
'data_class' => UserDetails::class,
'attr' => [
"placeholder" => 'Surname'
],
])
->add('email',TextType::class,[
'attr' => [
"placeholder" => 'Email'
]
])
->add('password',PasswordType::class,[
'attr' => [
"placeholder" => 'Password'
]
])
->add('confirmPassword',PasswordType::class,[
'attr' => [
"placeholder" => 'Confirm Password'
]
])
/* ->add('user_type',ChoiceType::class, [
'help' => 'Do you want to perform? Choose Artist account type. Do you want to employ artist? Choose Firm.',
'label' => "Account type",
'choices' => [
'None' => 0,
'firm' => 1,
'artist' => 2
],
'attr' => [
"class" => 'choice'
]
])*/
->add('user_type',EntityType::class, [
'class' => UserType::class,
'choice_label'=>'type',
/*'choice_label'=>'type',
'choice_value' => function ($entity) {
return $entity ? $entity->getId() : '';
},*/
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
After submitting input in form I get this data:
The problem is user_type sends as a string I suppose, but should as an object. Am I right?
In User.php
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\Table(name="`user`")
*/
class User extends UserDetails
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $email;
/**
* #ORM\Column(type="string", length=255)
*/
private $password;
private $confirmPassword;
/**
* #ORM\OneToOne(targetEntity=UserType::class, cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $user_type;
/**
* #ORM\OneToOne(targetEntity=UserDetails::class, cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $user_details;
/**
* #ORM\OneToMany(targetEntity=UserToOffert::class, mappedBy="user_", orphanRemoval=true)
*/
private $user_to_offert;
/**
* #ORM\OneToMany(targetEntity=Skill::class, mappedBy="user_", orphanRemoval=true)
*/
private $skill;
/**
* #ORM\OneToMany(targetEntity=Requirement::class, mappedBy="user_id", orphanRemoval=true)
*/
private $requirement;
public function __construct()
{
$this->user_to_offert = new ArrayCollection();
$this->skill = new ArrayCollection();
$this->requirement = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getUserType(): ?string
{
return $this->user_type;
}
public function setUserType(string $user_type): self
{
$this->user_type = $user_type;
return $this;
}
public function getUserDetails(): ?UserDetails
{
return $this->user_details;
}
public function setUserDetails(UserDetails $user_details): self
{
$this->user_details = $user_details;
return $this;
}
/**
* #return mixed
*/
public function getConfirmPassword()
{
return $this->confirmPassword;
}
/**
* #param mixed $confirmPassword
*/
public function setConfirmPassword($confirmPassword): void
{
$this->confirmPassword = $confirmPassword;
}
/**
* #return Collection|UserToOffert[]
*/
public function getUserToOffert(): Collection
{
return $this->user_to_offert;
}
public function addUserToOffert(UserToOffert $userToOffert): self
{
if (!$this->user_to_offert->contains($userToOffert)) {
$this->user_to_offert[] = $userToOffert;
$userToOffert->setUser($this);
}
return $this;
}
public function removeUserToOffert(UserToOffert $userToOffert): self
{
if ($this->user_to_offert->removeElement($userToOffert)) {
// set the owning side to null (unless already changed)
if ($userToOffert->getUser() === $this) {
$userToOffert->setUser(null);
}
}
return $this;
}
/**
* #return Collection|Skill[]
*/
public function getSkill(): Collection
{
return $this->skill;
}
public function addSkill(Skill $skill): self
{
if (!$this->skill->contains($skill)) {
$this->skill[] = $skill;
$skill->setUser($this);
}
return $this;
}
public function removeSkill(Skill $skill): self
{
if ($this->skill->removeElement($skill)) {
// set the owning side to null (unless already changed)
if ($skill->getUser() === $this) {
$skill->setUser(null);
}
}
return $this;
}
/**
* #return Collection|Requirement[]
*/
public function getRequirement(): Collection
{
return $this->requirement;
}
public function addRequirement(Requirement $requirement): self
{
if (!$this->requirement->contains($requirement)) {
$this->requirement[] = $requirement;
$requirement->setUser($this);
}
return $this;
}
public function removeRequirement(Requirement $requirement): self
{
if ($this->requirement->removeElement($requirement)) {
// set the owning side to null (unless already changed)
if ($requirement->getUser() === $this) {
$requirement->setUser(null);
}
}
return $this;
}
}
UserDetails.php:
<?php
namespace App\Entity;
use App\Repository\UserDetailsRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=UserDetailsRepository::class)
*/
class UserDetails
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\Column(type="string", length=255)
*/
private $surname;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $description;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $photo;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getSurname(): ?string
{
return $this->surname;
}
public function setSurname(string $surname): self
{
$this->surname = $surname;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getPhoto(): ?string
{
return $this->photo;
}
public function setPhoto(?string $photo): self
{
$this->photo = $photo;
return $this;
}
public function __toString() {
return $this->name;
}
}
In UserType.php:
<?php
namespace App\Entity;
/**
* #ORM\Entity(repositoryClass=UserTypeRepository::class)
*/
class UserType
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $type;
public function getId(): ?int
{
return $this->id;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
public function __toString() {
return $this->type;
}
}
If I remove __toString method I get an error:
Any ideas what am I doing wrong? Thank you for your time in advance. Have a nice day!

Symfony 4 - choice_value FormType not working

This is the method in my controller:
public function parentCat($parentId,$manOrWomen,Request $request){
$pr=new Product();
$products=$this->getDoctrine()->getRepository(Product::class)->listProductsParentCategory($parentId,$manOrWomen);
$form=$this->createForm(SearchProductType::class,$pr,['parentId'=>$parentId,'manOrWomen'=>$manOrWomen]);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$price=$request->request->get('search_product','price');
$name=$request->request->get('search_product','name');
$products=$this->getDoctrine()->getRepository(Product::class)->listSearchedProd($parentId,$manOrWomen,$price['price']
,$name['name']);
//$products=$this->getDoctrine()->getRepository(Product::class)->listSearchedProd($productPrice);
return $this->render('list_products/index.html.twig',['controller_name' => 'ListProductsController',
'form1'=>$form->createView(),'products'=>$products]);
}
else{
return $this->render('list_products/index.html.twig',['controller_name' => 'ListProductsController','form1'=>$form->createView()
,'products'=>$products]);
}
}
This is my Product class(Pruduct Entity):
class Product
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
*
* #ORM\Column(type="string", length=255)
* #Assert\Image(mimeTypes={"image/jpeg","image/png"})
*/
private $image;
/**
* #ORM\Column(type="integer")
*/
private $price;
/**
* #var Category[] | ArrayCollection
* #ORM\ManyToOne(targetEntity="App\Entity\Category")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* #var ManOrWomen[] | ArrayCollection
* #ORM\ManyToOne(targetEntity="App\Entity\ManOrWomen")
* #ORM\JoinColumn(name="manorwomen_id", referencedColumnName="id")
*/
private $manorwomen;
/**
* #param \DateTime $createdDate
*
* #ORM\Column(name="createdDate", type="datetime")
*/
private $createdDate;
/**
* Product constructor.
*/
public function __construct()
{
$this->createdDate=new \DateTime('now');
$this->category = new ArrayCollection();
$this->manorwomen=new ArrayCollection();
$this->undercategory=new ArrayCollection();
$this->parentCategory=new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name): self
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
public function getPrice()
{
return $this->price;
}
public function setPrice($price): self
{
$this->price = $price;
return $this;
}
/**
* #return Category[]|ArrayCollection
*/
public function getCategory()
{
return $this->category;
}
/**
* #param Category[]|ArrayCollection $category
*/
public function setCategory($category): void
{
$this->category = $category;
}
/**
* #return ManOrWomen[]|ArrayCollection
*/
public function getManorwomen()
{
return $this->manorwomen;
}
/**
* #param ManOrWomen[]|ArrayCollection $manorwomen
*/
public function setManorwomen($manorwomen): void
{
$this->manorwomen = $manorwomen;
}
/**
* #return DateTime
*/
public function getCreatedDate(): DateTime
{
return $this->createdDate;
}
/**
* #param DateTime $createdDate
*/
public function setCreatedDate(DateTime $createdDate): void
{
$this->createdDate = $createdDate;
}
This is my FormType for class Product:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$parentId = $options['parentId'];
$manOrWomen=$options['manOrWomen'];
$builder
->add('price',EntityType::class,[
'class'=>Product::class,
'choice_label'=>'price',
'choice_value' => 'price',
'placeholder'=>'Default',
'query_builder' => function (EntityRepository $er) use ($parentId,$manOrWomen) {
return $er->createQueryBuilder('product')
->innerJoin('product.category','c')
->addSelect('c')
->innerJoin('product.manorwomen','m')
->addSelect('m')
->where('c.parent_id=:parentId')
->andWhere('m.id=:manOrWomen')
->setParameters(['parentId'=>$parentId,'manOrWomen'=>$manOrWomen]);
},
'expanded'=>false,
'multiple'=>false
])
->add('name',EntityType::class,[
'class'=>Product::class,
'choice_label'=>'name',
'choice_value' => 'name',
'placeholder'=>'Default',
'query_builder' => function (EntityRepository $er) use ($parentId,$manOrWomen) {
return $er->createQueryBuilder('product')
->innerJoin('product.category','c')
->addSelect('c')
->innerJoin('product.manorwomen','m')
->addSelect('m')
->where('c.parent_id=:parentId')
->andWhere('m.id=:manOrWomen')
->setParameters(['parentId'=>$parentId,'manOrWomen'=>$manOrWomen]);
},
'expanded'=>false,
'multiple'=>false
])
->add('submit',SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Product::class
]);
$resolver->setRequired(
['parentId','manOrWomen']
);
}
I have problem with the request:
"price" => "44" (This is the price for the current item.This is okay.)
"name" => "44" (This must be the name of current item.)
I have 'choice_value'=>'name' but I get the price instead name.
If I change first choice_value with another value,the second choice_value becomes equal to her.Why?
When I remove addSelect from first EntityType works fine,but if I add more one EntityType,then I have the same problem - thirth EntityType value becomes equal to second value ('name').
I would say your entity is returning the price in the getter of the name or the setter of the price is setting the value of name.

How to get limited number of fields from embedded document with mongodb-odm?

I want to get the result of this mongodb command with Doctrine MongoDB ODM:
db.posts.find({_id: 3}, {comments: {$slice: [0, 5]}})
I was looking for it, but didn't find anything, neither in the documentation. If you have any idea, please help, thank you.
Here are my document classes:
/** #ODM\Document(db="dbname" collection="posts") */
class Posts{
/** #ODM\Id */
private $_id;
/** #ODM\Field(type="string") */
private $some_field;
/** #ODM\EmbedMany(targetDocument="Comment") */
private $comments = array();
public function getSomeField() { return $this->some_field; }
public function setSomeField($content) { $this->some_field = $content; }
public function getComments() { return $this->comments; }
public function addComment(Comment $comment) { $this->comments[] = $comment; }
}
/** #ODM\EmbeddedDocument */
class Comment {
/** #ODM\Field(type="string") */
private $timeStamp;
/** #ODM\Field(type="string") */
private $message;
/** #ODM\ReferenceOne(targetDocument="Users", simple=true) */
private $user_ref;
public function getTimeStamp() { return $this->timeStamp; }
public function setTimeStamp($str) { $this->timeStamp = $str;}
public function getMessage() { return $this->message; }
public function setMessage($str) { $this->message = $str; }
public function getUser() { return $this->user_ref; }
public function setUser(Users $user) { $this->user_ref = $user; }
}
While documentation on query builder's ->select() doesn't go much into details nor methods alike, following code will allow you to run your command:
$qb = $this->dm->createQueryBuilder(Posts::class)
->selectSlice('comments', 0, 5)
->field('_id')->equals(3);
$query = $qb->getQuery();
$results = $query->execute();

Doctrine ODM: Embedding multiple GridFS documents exception

I'm trying to embed a thumbnail image inside of it's main larger image in GridFS via Doctrine / Symfony 2.
The main image document is as follows,
<?php
namespace namespace\goes\here\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class FullSizeImage
{
/** #MongoDB\Id */
private $id;
/** #MongoDB\File */
private $file;
/** #MongoDB\String */
private $filename;
/** #MongoDB\String */
private $mimeType;
/** #MongoDB\Date */
private $uploadDate;
/** #MongoDB\Int */
private $userId;
/** #MongoDB\Int */
private $length;
/** #MongoDB\Int */
private $chunkSize;
/** #MongoDB\String */
private $md5;
/** #MongoDB\Collection */
private $tags = array();
/** #MongoDB\EmbedOne(targetDocument="Thumbnail") */
private $thumbnail;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getTags()
{
return $this->tags;
}
public function setTags($tags)
{
$this->tags = $tags;
}
public function getFile()
{
return $this->file;
}
public function setFile($file)
{
$this->file = $file;
}
public function getFilename()
{
return $this->filename;
}
public function setFilename($filename)
{
$this->filename = $filename;
}
public function getMimeType()
{
return $this->mimeType;
}
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
public function getChunkSize()
{
return $this->chunkSize;
}
public function getLength()
{
return $this->length;
}
public function getMd5()
{
return $this->md5;
}
public function getUploadDate()
{
return $this->uploadDate;
}
public function getUserId()
{
return $this->userId;
}
public function setUserId($userId)
{
$this->userId = $userId;
}
public function getThumbnail()
{
return $this->thumbnail;
}
public function setThumbnail($thumbnail)
{
$this->thumbnail = $thumbnail;
}
}
and the thumbnail document, that lives under the same namespace, is as follows,
<?php
namespace namespace\goes\here\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/** #MongoDB\EmbeddedDocument */
class Thumbnail
{
/** #MongoDB\Id */
private $id;
/** #MongoDB\File */
private $file;
/** #MongoDB\String */
private $filename;
/** #MongoDB\String */
private $mimeType;
/** #MongoDB\Date */
private $uploadDate;
/** #MongoDB\Int */
private $length;
/** #MongoDB\Int */
private $chunkSize;
/** #MongoDB\String */
private $md5;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getFile()
{
return $this->file;
}
public function setFile($file)
{
$this->file = $file;
}
public function getFilename()
{
return $this->filename;
}
public function setFilename($filename)
{
$this->filename = $filename;
}
public function getMimeType()
{
return $this->mimeType;
}
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
public function getChunkSize()
{
return $this->chunkSize;
}
public function getLength()
{
return $this->length;
}
public function getMd5()
{
return $this->md5;
}
public function getUploadDate()
{
return $this->uploadDate;
}
}
When I try to persist / flush the FullSizeImage,
$thumbnail = new Thumbnail();
$thumbnail->setFile($thumbPath);
$thumbnail->setFilename($thumbName);
$thumbnail->setMimeType($thumbMimeType);
$thumbnail->setUserId($user->getId());
$fsi = new FullSizeImage();
$fsi->setFile($file->getRealPath());
$fsi->setTags(array('tag', 'tag', 'tag'));
$fsi->setFilename($file->getFilename());
$fsi->setMimeType($file->getMimeType());
$fsi->setUserId($user->getId());
$fsi->setThumbnail($thumbnail);
$dm->persist($fsi);
$dm->flush();
I encounter this exception,
Could not store file: zero-length keys are not allowed, did you use $
with double quotes?
Am I missing something? Or is there a better way to go about storing these images and their relationship in mongo?
Field, which maps GridFS have to be the top-most-level document. It can be referenced by other documents, but it can't be embed by any other document. It's because GridFS implementation in Mongo ODM.
I've had a similiar issue some time ago. I've ended up with solution described above.
More details: https://github.com/doctrine/mongodb-odm/issues/911

Duplicate definition of column 'urbanization' on entity

I'm working with FOSUserBundle and I need to build Users Profile. This is what I did:
Create the User class and extends from BaseUser as FOSUser docs said
namespace Sunahip\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="Profile", mappedBy="user")
*/
protected $profile;
/**
* #ORM\ManyToMany(targetEntity="Sunahip\UserBundle\Entity\Group")
* #ORM\JoinTable(name="fos_user_user_group",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;
}
Create a Profile entity
namespace Sunahip\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* #ORM\Entity
* #ORM\Table(name="profile")
*/
class Profile extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="User", inversedBy="profile")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
/**
* #ORM\Column(name="register_type", type="smallint", length=1)
*/
protected $register_type;
/**
* #ORM\Column(name="rif", type="string", length=25)
*/
protected $rif;
/**
* #ORM\Column(name="ci", type="string", length=25)
*/
protected $ci;
/**
* #ORM\Column(name="firstname", type="string", length=25)
*/
protected $firstname;
/**
* #ORM\Column(name="lastname", type="string", length=25)
*/
protected $lastname;
/**
* #ORM\Column(name="state", type="string", length=150)
*/
protected $state;
/**
* #ORM\Column(name="city", type="string", length=150)
*/
protected $city;
/**
* #ORM\Column(name="town", type="string", length=150)
*/
protected $town;
/**
* #ORM\Column(name="urbanization", type="string", length=150)
*/
protected $urbanization;
/**
* #ORM\Column(name="urbanization", type="string", length=150)
*/
protected $street;
/**
* #ORM\Column(name="aparment", type="string", length=150)
*/
protected $aparment;
/**
* #ORM\Column(name="aparment_no", type="string", length=150)
*/
protected $aparment_no;
/**
* #ORM\Column(name="reference", type="string", length=250)
*/
protected $reference;
/**
* #ORM\Column(name="zipcode", type="string", length=250)
*/
protected $zipcode;
/**
* #ORM\Column(name="fax", type="string", length=250)
*/
protected $fax;
/**
* #ORM\Column(name="local_phone", type="string", length=250)
*/
protected $local_phone;
/**
* #ORM\Column(name="movil_phone", type="string", length=250)
*/
protected $movil_phone;
/**
* #ORM\Column(name="alt_email", type="string", length=250)
*/
protected $alt_email;
/**
* #ORM\Column(name="alt_email", type="string", length=250)
*/
protected $website;
public function getId()
{
return $this->id;
}
public function setUser(User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
public function setRegisterType($register_type)
{
$this->register_type = $register_type;
}
public function getRegisterType()
{
return $this->register_type;
}
public function setRif($rif)
{
$this->rif = $rif;
}
public function getRif()
{
return $this->rif;
}
public function setCI($ci)
{
$this->ci = $ci;
}
public function getCI()
{
return $this->ci;
}
public function setFirstname($firstname)
{
$this->firstname = $firstname;
}
public function getFirstname()
{
return $this->firstname;
}
public function setLastname($lastname)
{
$this->lastname = $lastname;
}
public function getLastname()
{
return $this->lastname;
}
public function setState($state)
{
$this->state = $state;
}
public function getState()
{
return $this->state;
}
public function setCity($city)
{
$this->city = $city;
}
public function getCity()
{
return $this->city;
}
public function setTown($town)
{
$this->town = $town;
}
public function getTown()
{
return $this->town;
}
public function setUrbanization($urbanization)
{
$this->urbanization = $urbanization;
}
public function getUrbanization()
{
return $this->urbanization;
}
public function setStreet($street)
{
$this->street = $street;
}
public function getStreet()
{
return $this->street;
}
public function setAparment($aparment)
{
$this->aparment = $aparment;
}
public function getAparment()
{
return $this->aparment;
}
public function setAparmentNo($aparment_no)
{
$this->aparment_no = $aparment_no;
}
public function getAparmentNo()
{
return $this->aparment_no;
}
public function setReference($reference)
{
$this->reference = $reference;
}
public function getReference()
{
return $this->reference;
}
public function setZipcode($zipcode)
{
$this->zipcode = $zipcode;
}
public function getZipcode()
{
return $this->zipcode;
}
public function setFax($fax)
{
$this->fax = $fax;
}
public function getFax()
{
return $this->fax;
}
public function setLocalPhone($local_phone)
{
$this->local_phone = $local_phone;
}
public function getLocalPhone()
{
return $this->local_phone;
}
public function setMovilPhone($movil_phone)
{
$this->movil_phone = $movil_phone;
}
public function getMovilPhone()
{
return $this->movil_phone;
}
public function setAltEmail($alt_email)
{
$this->alt_email = $alt_email;
}
public function getAltEmail()
{
return $this->alt_email;
}
public function setWebsite($website)
{
$this->website = $website;
}
public function getWebsite()
{
return $this->website;
}
}
Now, I'm trying to validate that entities by running the command doctrine:schema:validate and I get this error:
[Doctrine\ORM\Mapping\MappingException] Duplicate definition of
column 'urbanization' on entity 'Sunahip\UserBundle\Entity\Profile' in
a field or discriminator column mapping.
My questions:
I don't know what is wrong and also don't know what the error means is the first time I got this error.
I don't know if I'm building users profiles in the right way I mean if I should extends from BaseUser or from User
Can I give some help here? Advices? Ideas?
You have (had) basically two probles here:
Duplicated urbanization column name somewhere there which needs to be removed. Only one column with the same name is allowed
Duplicated #ORM\Id annotation in your Profile entity. Remove one from $user because it is not your Id