I have some problem with colection in zf2 and doctryne.
Problem: I add some client and need have some multiselect.
ClientEntity
/**
* #ORM\MappedSuperclass
*/
class Client {
...
/**
* #ORM\ManyToOne(targetEntity="\Module\Model\Job")
* #ORM\JoinColumn(name="job_id", referencedColumnName="id")
*/
protected $job;
/**
* #ORM\OneToMany(targetEntity="SomeOption", mappedBy="job", cascade= {"persist", "remove"})
* */
protected $someOption;
...
public function __construct() {
$this->someOption= new ArrayCollection();
}
OptionEntity
/**
* #ORM\MappedSuperclass
*/
class SomeOption{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="\Module\Model\Client")
* #ORM\JoinColumn(name="job_id", referencedColumnName="id")
* */
protected $job;
/**
* #ORM\Column(type="string", nullable=false)
*/
protected $option;
}
Bought model have getter and setter, in Client model have:
public function addSomeOption(Collection $options) {
foreach ($options as $option) {
$option->setJob($this);
$this->someOption->add($option);
}
return $this;
}
public function removeSomeOption(Collection $options) {
foreach ($options as $option) {
$option->setJob(null);
$this->someOption->removeElement($option);
}
return $this;
}
public function getSomeOption() {
return $this->someOption;
}
Form:
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'someOption',
'attributes' => array(
'id' => 'someOption',
),
'options' => array(
'label' => 'Rozliczenie',
'value_options' => array(
array('value' => '1r', 'label' => '1/rok'),
array('value' => '1m', 'label' => '1/miesiąc'),
array('value' => '1w', 'label' => '1/tydzień'),
array('value' => '1d', 'label' => '1/dzień'),
),
),
'attributes' => array(
'class' => 'span12 settlement chosen',
'multiple' => 'multiple'
)
));
after this i need have 1 row of client and 1+ row of someOption, may any help to repair code ? or much more will be explain what i make wrong.
Related
I have two tables (Player & Historique) that have a OneToMany association. In my PlayerType form, I have a CollectionType with an entry_type to my HistoriqueType. My question is about the order in which the data from HistoriqueType arrives. For the moment, it appears in ASC order of the id. But I would like it to appear in ASC order of the years (season).
Here are my two entities :
<?php
/**
* #ORM\Entity(repositoryClass=PlayerRepository::class)
*/
class Player
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=Historique::class, mappedBy="player", cascade={"persist"}, orphanRemoval = true)
*/
public $playerHistoriques;
public function __construct()
{
$this->playerHistoriques = new ArrayCollection();
}
And my Historique Class :
<?php
/**
* #ORM\Entity(repositoryClass=HistoriqueRepository::class)
*/
class Historique
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=Club::class, inversedBy="historiques")
* #ORM\JoinColumn(nullable=true)
*/
private $club;
/**
* #ORM\ManyToOne(targetEntity=Season::class, inversedBy="historiques")
* #ORM\JoinColumn(nullable=true)
* #ORM\OrderBy({"season" = "ASC"})
*/
private $season;
/**
* #ORM\ManyToOne(targetEntity=Player::class, inversedBy="playerHistoriques")
* #ORM\JoinColumn(nullable=true)
*/
private $player;
/**
* #ORM\ManyToOne(targetEntity=Position::class, inversedBy="historiques")
*/
private $position;
My PlayerType :
<?php
class PlayerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('playerHistoriques', CollectionType::class, [
'entry_type' => HistoriqueType::class,
'entry_options' => [
'label' => false
],
'by_reference' => false,
'allow_add' => true
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Player::class,
]);
}
}
And My HistoriqueType:
<?php
class HistoriqueType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('club', EntityType::class, [
'class' => Club::class,
'choice_label' => 'name',
'label' => false,
'required' => false,
'placeholder' => '-',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('c')
->orderBy('c.name', 'ASC');
}
])
->add('season', EntityType::class, [
'class' => Season::class,
'choice_label' => 'year',
'label' => false,
'placeholder' => '-',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('s')
->orderBy('s.year', 'ASC');
}
])
->add('position', EntityType::class, [
'class' => Position::class,
'choice_label' => 'position',
'label' => false,
'placeholder' => '-',
'required' => false
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Historique::class,
'method' => 'get',
'csrf_protection' => false
]);
}
public function getBlockPrefix() {
return '';
}
}
In my edit form, I would like to order my collectionType by 'season' => 'ASC', in order to have the years in chronological order even in my edit form.
I have tried a query_builder like so in my PlayerType :
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('h')
->orderBy('h.season', 'ASC');
}
But it generated an error since collectionTypes cannot have queries in them.
I have tried to order it automatically in my PlayerEntity #ORM\OrderBy({"season" = "ASC"}) but it didn't work.
In your Historique Entity change the order by to year instead of season (I believe in your other form you are sorting by the year so hopefully this is the property you are looking to sort by).
/**
* #ORM\ManyToOne(targetEntity=Season::class, inversedBy="historiques")
* #ORM\JoinColumn(nullable=true)
* #ORM\OrderBy({"year" = "ASC"})
*/
private $season;
You should be able to remove the query builder now, unless you need to narrow the selection.
OrderBy must be in Palyer entity in OneToMany relation not in Historique
/**
*#ORM\OneToMany(targetEntity=Historique::class, mappedBy="player", cascade={"persist"}, orphanRemoval = true)
*#ORM\OrderBy({"season" = "ASC"})
*/
public $playerHistoriques;
In a previous question (Symfony Check if at least one of two fields isn't empty on form validation) I had asked help for form validation using Callback. The answer given by #hous was right, but it doesn't work for elements in a CollectionType, reason why I'm opening a new question.
Based on the previous answer I have done the following:
Here is my "mother" Form:
class BookingVisitorType extends AbstractType
{
private $router;
private $translator;
public function __construct()
{
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('visitors', CollectionType::class, [
'entry_type' => VisitorType::class,
'label' => 'entity.booking.visitors',
'allow_add' => true,
'allow_delete' => true,
'delete_empty' => true,
'by_reference' => false,
'entry_options' => [
'label' => false,
'delete-url' => $options['visitor-delete-url']
],
'constraints' =>[
new Count([
'min' => 1,
'minMessage' => 'validator.visitor.at-least-one-visitor',
'max' => $options['numberOfPlaces'],
'maxMessage' => 'validator.visitor.cannot-have-more-visitor-than-spaces',
'exactMessage' => 'validator.visitor.exact-message'
])
]
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Booking::class,
'numberOfPlaces' => 1,
'visitor-delete-url' => ''
]);
}
}
Here is my "son" Form:
class VisitorType extends AbstractType
{
private $phone;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', TextType::class, [
'label' => 'entity.visitor.first-name',
'constraints' => [
new NotBlank(),
new Length([
'min' => 2,
'max' => 255
]),
new Regex([
'pattern' => "/[\pL\s\-]*/",
'message' => 'validator.visitor.not-valide-first-name'
])
]
])
->add('phone', TextType::class, [
'label' => 'entity.visitor.phone-number',
'required' => false,
'constraints' => [
new Regex([
'pattern' => "/[0-9\s\.\+]*/",
'message' => 'validator.visitor.not-valide-phone-number'
]),
new Callback(function($phone, ExecutionContextInterface $context){
$this->phone = $phone;
}),
]
])
->add('email', TextType::class, [
'label' => 'entity.visitor.email',
'required' => false,
'constraints' => [
new Email(),
new Callback(function($email, ExecutionContextInterface $context){
if ($this->phone == null && $email == null) {
$context->buildViolation('validator.visitor.email-or-phone-required')->addViolation();
}
}),
]
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Visitor::class,
'error_bubbling' => false,
'delete-url' => '',
]);
}
}
My "booking" (shortened) class:
/**
* #ORM\Entity(repositoryClass="App\Repository\BookingRepository")
*/
class Booking
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Visitor", mappedBy="booking", orphanRemoval=true, cascade={"persist"})
* #Assert\Valid
*/
private $visitors;
}
And finally my "visitor" (shortened) class:
/**
* #ORM\Entity(repositoryClass="App\Repository\VisitorRepository")
*/
class Visitor
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=45, nullable=true)
*/
private $phone;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $email;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Booking", inversedBy="visitors")
* #ORM\JoinColumn(nullable=false)
*/
private $booking;
/**
* #Assert\Callback
*/
public function validateAtLeastEmailOrPhone(ExecutionContextInterface $context, $payload)
{
if ($this->getPhone() === null && $this->getEmail() === null) {
$context->buildViolation('validator.visitor.email-or-phone-required-for-all')->addViolation();
}
}
}
I've been able to workaround the problem by adding a property to my VisitorType form that I define with the Callback constraint on the phone value and then check it with a Callback constraint on the email field, but it doesn't seem very "good practice".
If I only try to call the Callback constraint I get the following error message: "Warning: get_class() expects parameter 1 to be object, string given"
Any help is highly appreciated!
Instead of an callback function you could create your own Constraint. Then the Check would be reusable.
I've been using this to check the password on registration against custom rules.
On Symfony 2.8, I got the following entities:
Contact:
class Contact
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column
* #Assert\NotBlank
*/
protected $name;
/**
* #ORM\OneToMany(targetEntity="EmailContact", mappedBy="contact", cascade={"persist"})
* #Assert\Valid
*/
protected $emails;
// ...
/**
* Add emails
*
* #param \AppBundle\Entity\EmailContact $emails
* #return Contact
*/
public function addEmail(\AppBundle\Entity\EmailContact $emails)
{
$this->emails[] = $emails;
$emails->setContact($this); //this line added by me
return $this;
}
// ...
EmailContact:
class EmailContact
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column
* #Assert\NotBlank
*/
protected $email;
/**
* #ORM\ManyToOne(targetEntity="Contact", inversedBy="emails")
* #ORM\JoinColumn(nullable=false)
*/
protected $contact;
// ...
The rest of the methods were automatically generated by the doctrine:generate:entities command.
My forms are as follows:
ContactType:
class ContactType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', null, [
'label' => 'contact.name',
])
->add('emails', CollectionType::class, [
'label' => false,
'entry_options' => array('label' => false),
'entry_type' => EmailContactType::class,
'allow_add' => true,
'allow_delete' => true,
'delete_empty' => true,
'prototype' => true,
])
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Contact'
]);
}
EmailContactType:
class EmailContactType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class, [
'label' => 'emailContact.email',
])
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\EmailContact'
]);
}
I do the javascript to add extra fields to the request, and submit it. Example request (from Symfony Profiler):
[
name => test4,
emails => [
0 => [
email => t#t.t4
],
1 => [
email => t#t.t5
]
],
_token => ...
]
But I get the following error:
An exception occurred while executing 'INSERT INTO email_contact ...
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'contact_id' cannot be null
Debugging, I see that the addEmail method above never gets called. What is happening here?
You missed by_reference => false in form collection definition
->add('emails', CollectionType::class, [
'label' => false,
'entry_options' => array('label' => false),
'entry_type' => EmailContactType::class,
'allow_add' => true,
'allow_delete' => true,
'delete_empty' => true,
'prototype' => true,
'by_reference' => false; // <--- you missed this
]);
Take a look here
Your code should run as expected after this modification.
Moreover remember that if you have a setEmails() method inside Contact class, the framework end up to calling it and so you need (for each element of the collection) to set contact as well (as you're correctly doing in addEmails())
I've got the next error in my development:
[Doctrine\ORM\Mapping\MappingException]
The target-entity Game\Entity\UserEntity cannot be found in
'Game\Entity\ChallengeRosterEntity#user'.
I have two modules:
User
Game
In these modules I have defined several entities where one of them is relationed with other entity which belongs to other module.
\Game\Entity\ChallengeRosterEntity.php
<?php
namespace Game\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use User\Entity;
/** #ORM\Entity
* #ORM\Table(name="challenge_roster")
* #ORM\Entity(repositoryClass="Game\Repository\ChallengeRosterRepository")
*/
class ChallengeRosterEntity{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="ChallengeEntity", inversedBy="challengeRoster")
*
**/
protected $challenge;
/**
* #ORM\ManyToOne(targetEntity="UserEntity", inversedBy="userInRosters")
*
**/
protected $user;
/**
* #ORM\Column(type="integer", nullable = true)
*/
protected $points;
/**
* Fecha y hora de creación del roster del desafío por parte del usuario
*
* #ORM\Column(type="datetime", nullable = false)
*/
protected $date;
/**
* #ORM\ManyToMany(targetEntity="BasketballPlayerStatsEntity")
* #ORM\JoinTable(name="players_roster",
* joinColumns={#ORM\JoinColumn(name="challenge_roster_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="basketball_player_stats_id", referencedColumnName="id")}
* )
**/
protected $basketballPlayers;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set points
*
* #param integer $points
* #return ChallengeRosterEntity
*/
public function setPoints($points)
{
$this->points = $points;
return $this;
}
/**
* Get points
*
* #return integer
*/
public function getPoints()
{
return $this->points;
}
/**
* Set date
*
* #param \DateTime $date
* #return ChallengeRosterEntity
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set challenge
*
* #param \Game\Entity\ChallengeEntity $challenge
* #return ChallengeRosterEntity
*/
public function setChallenge(\Game\Entity\ChallengeEntity $challenge = null)
{
$this->challenge = $challenge;
return $this;
}
/**
* Get challenge
*
* #return \Game\Entity\ChallengeEntity
*/
public function getChallenge()
{
return $this->challenge;
}
/**
* Set user
*
* #param \Game\Entity\UserEntity $user
* #return ChallengeRosterEntity
*/
public function setUser(\Game\Entity\UserEntity $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \Game\Entity\UserEntity
*/
public function getUser()
{
return $this->user;
}
/**
* Constructor
*/
public function __construct()
{
$this->basketballPlayers = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add basketballPlayers
*
* #param \Game\Entity\BasketballPlayerStatsEntity $basketballPlayers
* #return ChallengeRosterEntity
*/
public function addBasketballPlayer(\Game\Entity\BasketballPlayerStatsEntity $basketballPlayers)
{
$this->basketballPlayers[] = $basketballPlayers;
return $this;
}
/**
* Remove basketballPlayers
*
* #param \Game\Entity\BasketballPlayerStatsEntity $basketballPlayers
*/
public function removeBasketballPlayer(\Game\Entity\BasketballPlayerStatsEntity $basketballPlayers)
{
$this->basketballPlayers->removeElement($basketballPlayers);
}
/**
* Get basketballPlayers
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBasketballPlayers()
{
return $this->basketballPlayers;
}
}
\User\Entity\UserEntity.php
<?php
namespace User\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Game\Entity;
/** #ORM\Entity
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="User\Repository\UserRepository")
*/
class UserEntity{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string", length = 20, nullable = false)
*/
protected $nick;
/**
* #ORM\Column(type="string", length = 100, nullable = false)
*/
protected $email;
/**
* #ORM\Column(type="string", length = 100, nullable = true)
*/
protected $thumb;
/**
* #ORM\Column(type="integer", nullable = false)
*/
protected $totalRetodones;
/**
* #ORM\Column(type="integer", nullable = false)
*/
protected $challengeWon;
/**
* #ORM\Column(type="integer", nullable = false)
*/
protected $points;
/**
* #ORM\Column(type="integer", nullable = false)
*/
protected $spentRetodones;
/**
* #ORM\Column(type="string", length = 100, nullable = true)
*/
protected $twitterAccount;
/**
* #ORM\Column(type="string", length = 100, nullable = true)
*/
protected $facebookAccount;
/**
* #ORM\OneToMany(targetEntity="StatusEntity", mappedBy="users")
**/
protected $status;
/**
* #ORM\OneToMany(targetEntity="UserEntity", mappedBy="refered")
**/
protected $referedBy;
/**
* #ORM\ManyToOne(targetEntity="UserEntity", inversedBy="referedBy")
* #ORM\JoinColumn(name="refered_id", referencedColumnName="id")
**/
protected $refered;
/**
* #ORM\ManyToMany(targetEntity="UserEntity", mappedBy="myFriends")
**/
protected $friendsWithMe;
/**
* #ORM\ManyToMany(targetEntity="UserEntity", inversedBy="friendsWithMe")
* #ORM\JoinTable(name="user_friends",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="friend_user_id", referencedColumnName="id")}
* )
**/
protected $myFriends;
/**
* #ORM\ManyToOne(targetEntity="ChallengeEntity", inversedBy="userChallenger")
*
**/
//protected $usersChallenger;
/**
* #ORM\ManyToOne(targetEntity="ChallengeEntity", inversedBy="userChallenged")
*
**/
//protected $usersChallenged;
/**
* #ORM\ManyToOne(targetEntity="ChallengeRosterEntity", inversedBy="user")
*
**/
protected $userInRosters;
/**
* Constructor
*/
public function __construct()
{
$this->status = new \Doctrine\Common\Collections\ArrayCollection();
$this->referedBy = new \Doctrine\Common\Collections\ArrayCollection();
$this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
$this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nick
*
* #param string $nick
* #return UserEntity
*/
public function setNick($nick)
{
$this->nick = $nick;
return $this;
}
/**
* Get nick
*
* #return string
*/
public function getNick()
{
return $this->nick;
}
/**
* Set email
*
* #param string $email
* #return UserEntity
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set thumb
*
* #param string $thumb
* #return UserEntity
*/
public function setThumb($thumb)
{
$this->thumb = $thumb;
return $this;
}
/**
* Get thumb
*
* #return string
*/
public function getThumb()
{
return $this->thumb;
}
/**
* Set totalRetodones
*
* #param integer $totalRetodones
* #return UserEntity
*/
public function setTotalRetodones($totalRetodones)
{
$this->totalRetodones = $totalRetodones;
return $this;
}
/**
* Get totalRetodones
*
* #return integer
*/
public function getTotalRetodones()
{
return $this->totalRetodones;
}
/**
* Set challengeWon
*
* #param integer $challengeWon
* #return UserEntity
*/
public function setChallengeWon($challengeWon)
{
$this->challengeWon = $challengeWon;
return $this;
}
/**
* Get challengeWon
*
* #return integer
*/
public function getChallengeWon()
{
return $this->challengeWon;
}
/**
* Set points
*
* #param integer $points
* #return UserEntity
*/
public function setPoints($points)
{
$this->points = $points;
return $this;
}
/**
* Get points
*
* #return integer
*/
public function getPoints()
{
return $this->points;
}
/**
* Set spentRetodones
*
* #param integer $spentRetodones
* #return UserEntity
*/
public function setSpentRetodones($spentRetodones)
{
$this->spentRetodones = $spentRetodones;
return $this;
}
/**
* Get spentRetodones
*
* #return integer
*/
public function getSpentRetodones()
{
return $this->spentRetodones;
}
/**
* Set twitterAccount
*
* #param string $twitterAccount
* #return UserEntity
*/
public function setTwitterAccount($twitterAccount)
{
$this->twitterAccount = $twitterAccount;
return $this;
}
/**
* Get twitterAccount
*
* #return string
*/
public function getTwitterAccount()
{
return $this->twitterAccount;
}
/**
* Set facebookAccount
*
* #param string $facebookAccount
* #return UserEntity
*/
public function setFacebookAccount($facebookAccount)
{
$this->facebookAccount = $facebookAccount;
return $this;
}
/**
* Get facebookAccount
*
* #return string
*/
public function getFacebookAccount()
{
return $this->facebookAccount;
}
/**
* Add status
*
* #param \User\Entity\StatusEntity $status
* #return UserEntity
*/
public function addStatus(\User\Entity\StatusEntity $status)
{
$this->status[] = $status;
return $this;
}
/**
* Remove status
*
* #param \User\Entity\StatusEntity $status
*/
public function removeStatus(\User\Entity\StatusEntity $status)
{
$this->status->removeElement($status);
}
/**
* Get status
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getStatus()
{
return $this->status;
}
/**
* Add referedBy
*
* #param \User\Entity\UserEntity $referedBy
* #return UserEntity
*/
public function addReferedBy(\User\Entity\UserEntity $referedBy)
{
$this->referedBy[] = $referedBy;
return $this;
}
/**
* Remove referedBy
*
* #param \User\Entity\UserEntity $referedBy
*/
public function removeReferedBy(\User\Entity\UserEntity $referedBy)
{
$this->referedBy->removeElement($referedBy);
}
/**
* Get referedBy
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getReferedBy()
{
return $this->referedBy;
}
/**
* Set refered
*
* #param \User\Entity\UserEntity $refered
* #return UserEntity
*/
public function setRefered(\User\Entity\UserEntity $refered = null)
{
$this->refered = $refered;
return $this;
}
/**
* Get refered
*
* #return \User\Entity\UserEntity
*/
public function getRefered()
{
return $this->refered;
}
/**
* Add friendsWithMe
*
* #param \User\Entity\UserEntity $friendsWithMe
* #return UserEntity
*/
public function addFriendsWithMe(\User\Entity\UserEntity $friendsWithMe)
{
$this->friendsWithMe[] = $friendsWithMe;
return $this;
}
/**
* Remove friendsWithMe
*
* #param \User\Entity\UserEntity $friendsWithMe
*/
public function removeFriendsWithMe(\User\Entity\UserEntity $friendsWithMe)
{
$this->friendsWithMe->removeElement($friendsWithMe);
}
/**
* Get friendsWithMe
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFriendsWithMe()
{
return $this->friendsWithMe;
}
/**
* Add myFriends
*
* #param \User\Entity\UserEntity $myFriends
* #return UserEntity
*/
public function addMyFriend(\User\Entity\UserEntity $myFriends)
{
$this->myFriends[] = $myFriends;
return $this;
}
/**
* Remove myFriends
*
* #param \User\Entity\UserEntity $myFriends
*/
public function removeMyFriend(\User\Entity\UserEntity $myFriends)
{
$this->myFriends->removeElement($myFriends);
}
/**
* Get myFriends
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMyFriends()
{
return $this->myFriends;
}
/**
* Set userInRosters
*
* #param \User\Entity\ChallengeRosterEntity $userInRosters
* #return UserEntity
*/
public function setUserInRosters(\User\Entity\ChallengeRosterEntity $userInRosters = null)
{
$this->userInRosters = $userInRosters;
return $this;
}
/**
* Get userInRosters
*
* #return \User\Entity\ChallengeRosterEntity
*/
public function getUserInRosters()
{
return $this->userInRosters;
}
}
Doctrine 2 has the next configuration in each file.
\Game\config\module.config.php
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* #link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* #copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Game;
return array(
'router' => array(
'routes' => array(
/* 'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
), */
// The following is a route to simplify getting started creating
// new controllers and actions without needing to create a new
// module. Simply drop new controllers in, and you can access them
// using the path /application/:controller/:action
'application' => array(
'type' => 'Literal',
'options' => array(
'route' => '/juego',
'defaults' => array(
'__NAMESPACE__' => 'Game\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
'Zend\Log\LoggerAbstractServiceFactory',
),
'aliases' => array(
'translator' => 'MvcTranslator',
),
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
'controllers' => array(
'invokables' => array(
'Game\Controller\Index' => 'Game\Controller\IndexController'
),
),
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'game/index/index' => __DIR__ . '/../view/game/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
// Doctrine config
'doctrine' => array(
'driver' => array(
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
)
)
)
),
// Placeholder for console routes
'console' => array(
'router' => array(
'routes' => array(
),
),
),
);
\User\config\module.config.php
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* #link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* #copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace User;
return array(
'router' => array(
'routes' => array(
// The following is a route to simplify getting started creating
// new controllers and actions without needing to create a new
// module. Simply drop new controllers in, and you can access them
// using the path /application/:controller/:action
'application' => array(
'type' => 'Literal',
'options' => array(
'route' => '/user',
'defaults' => array(
'__NAMESPACE__' => 'User\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
'Zend\Log\LoggerAbstractServiceFactory',
),
'aliases' => array(
'translator' => 'MvcTranslator',
),
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
'controllers' => array(
'invokables' => array(
'User\Controller\Index' => 'User\Controller\IndexController'
),
),
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'user/index/index' => __DIR__ . '/../view/user/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
// Doctrine config
'doctrine' => array(
'driver' => array(
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
)
)
)
),
// Placeholder for console routes
'console' => array(
'router' => array(
'routes' => array(
),
),
),
);
What am I doing wrong?
I have been searching before for an answer for this problem but after hours I need to ask you.
I have one Entity called Pedidos, that have another entity related called PedidosMateriales, as you can see:
(...)
/**
* Pedidos
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="ochodoscuatro\IntranetBundle\Entity\PedidosRepository")
*/
class Pedidos
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
(...)
/**
* #ORM\OneToMany(targetEntity="PedidosMateriales", mappedBy="pedido")
*/
private $pedidosmateriales;
public function __construct() {
$this->pedidosmateriales = new \Doctrine\Common\Collections\ArrayCollection();
$this->pagos = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addPedidosmateriales(\ochodoscuatro\IntranetBundle\Entity\PedidosMateriales $pedidosmateriales){
$this->pedidosmateriales[] = $pedidosmateriales;
}
public function getPedidosmateriales(){
return $this->pedidosmateriales;
}
(...)
}
When I submit a form, if I get $_POST, I can see all the information good there, but just after doing
$form->handleRequest($request);
I get this error:
Neither the property "pedidosmateriales" nor one of the methods "addPedidosmaterial()", "addPedidosmateriale()", "setPedidosmateriales()", "__set()" or "__call()" exist and have public access in class "ochodoscuatro\IntranetBundle\Entity\Pedidos".
But I have them already written!
I've read that with "multiple" => true I could get the answer, but it launch another error telling that the option "multiple" does not exist.
My form is this:
$builder->add('fechapedido', 'date', array(//Fecha del pedido
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'attr' => array('class' => 'datepicker'),
'data' => new \DateTime() //Valor (Fecha actual)
))
->add('cliente', 'entity', array(
'class' => 'ochodoscuatroIntranetBundle:Clientes',
'property' => 'nombre',
'empty_value' => 'Nombre cliente'))//Nombre del "placeholder"
->add('pedidosmateriales', 'collection', array('type' => new PedidosMaterialesType(), 'allow_add' => true, 'by_reference' => false,));
}