Editing manytomany association doctrine2 and zf2 - php

I have a scenario like this: Hmo has a bidirectional Many2Many association with Hcp. What i mean is Hmo can add Hcp, Hcp should be able to view its Hmos and view some other information about an Hmo.
I have already created several Hmos and Hcps so the actual association is when editing Hmos in order to select Hcps to make association i kept getting an error:
Argument 1 passed to Hmo\Entity\Hmos::addHcp() must be an instance of Hcp\Entity\Hcps, instance of Doctrine\Common\Collections\ArrayCollection given, called in /var/www/insta/vendor/doctrine/doctrine-module/src/DoctrineModule/Stdlib/Hydrator/Strategy/AllowRemoveByValue.php on line 61 and defined in /var/www/insta/module/Hmo/src/Hmo/Entity/Hmos.php on line 58
Hcps.php
<?php
namespace Hcp\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Hmo\Entity\Hmos;
/** #ORM\Entity */
class Hcps
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/** #ORM\Column(type="string") */
protected $name;
/** #ORM\Column(type="string") */
protected $address;
/** #ORM\Column(type="string") */
protected $telno;
/** #ORM\Column(type="string") */
protected $email;
/** #ORM\Column(type="string") */
protected $typeoffac;
/** #ORM\Column(type="string") */
protected $catofreg;
/** #ORM\Column(type="string") */
protected $sregno;
/** #ORM\Column(type="string") */
protected $directorname;
/** #ORM\Column(type="date", nullable=true) */
protected $regdate;
/** #ORM\Column(type="time", nullable=true) */
protected $regtime;
/** #ORM\Column(type="datetime", nullable=true) */
protected $regdatetime;
/** #ORM\Column(type="datetime", nullable=true) */
protected $lastlogin;
/**
*#var \Doctrine\Common\Collections\ArrayCollection
* #ORM\ManyToMany(targetEntity="Hmo\Entity\Hmos", mappedBy="hcp")
*/
protected $hmo;
public function __constructor()
{
$this->hmo = new ArrayCollection();
}
public function addHmo(Hmos $hmo)
{
if ($this->hmo->contains($hmo)) {
return;
}
$this->hmo->add($hmo);
$hmo->addHcp($this);
}
public function setHmo(Hmos $hmo = null)
{
$this->hmo = $hmo;
}
public function getHmo()
{
return $this->hmo;
}
public function setLastlogin($lastlogin)
{
$this->lastlogin = $lastlogin;
return $this;
}
public function getLastlogin()
{
return $this->lastlogin;
}
public function setRegDatetime($regdatetime)
{
$this->regdatetime = $regdatetime;
return $this;
}
public function getRegdatetime()
{
return $this->regdatetime;
}
public function setRegtime($regtime)
{
$this->regtime = $regtime;
return $this;
}
public function getRegtime()
{
return $this->regtime;
}
public function setRegdate($regdate)
{
$this->regdate = $regdate;
return $this;
}
public function getRegdate()
{
return $this->regdate;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getId()
{
return $this->id;
}
public function setDirectorname($directorname)
{
$this->directorname = $directorname;
return $this;
}
public function getDirectorname()
{
return $this->directorname;
}
public function setSregno($sregno)
{
$this->sregno = $sregno;
return $this;
}
public function getSregno()
{
return $this->sregno;
}
public function setCatofreg($cof)
{
$this->catofreg = cof;
return $this;
}
public function getCatofreg()
{
return $this->catofreg;
}
public function setTypeoffac($tof)
{
$this->typeoffac = $tof;
return $this;
}
public function getTypeoffac()
{
return $this->typeoffac;
}
public function setTelno($telno)
{
$this->telno = $telno;
return $this;
}
public function getTelno()
{
return $this->telno;
}
public function setAddress($address)
{
$this->address = $address;
return $this;
}
public function getAddress()
{
return $this->address;
}
public function setName($name)
{
$this->name = $name;
return $name;
}
public function getName()
{
return $this->name;
}
public function setEmail($email)
{
$this->email = $email;
return $email;
}
public function getEmail()
{
return $this->email;
}
public function populate($data = array())
{
$this->id = $data['id'];
$this->name = $data['name'];
$this->address = $data['address'];
$this->telno = $data['telno'];
$this->email = $data['email'];
$this->typeoffac = $data['typeoffac'];
$this->catofreg = $data['catofreg'];
$this->sregno = $data['sregno'];
$this->directorname = $data['directorname'];
}
}
Hmos.php
<?php
namespace Hmo\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Hcp\Entity\Hcps;
/** #ORM\Entity */
class Hmos
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/** #ORM\Column(type="string") */
protected $nameofhmo;
/** #ORM\Column(type="string") */
protected $headoffice;
/** #ORM\Column(type="string") */
protected $telno;
/** #ORM\Column(type="string") */
protected $email;
/** #ORM\Column(type="string") */
protected $doincor;
/** #ORM\Column(type="string") */
protected $rcno;
/** #ORM\Column(type="string") */
protected $ceoname;
/** #ORM\Column(type="string") */
protected $bankers;
/** #ORM\Column(type="date", nullable=true) */
protected $regdate;
/** #ORM\Column(type="time", nullable=true) */
protected $regtime;
/** #ORM\Column(type="datetime", nullable=true) */
protected $regdatetime;
/** #ORM\Column(type="datetime", nullable=true) */
protected $lastlogin;
/**
* #ORM\ManyToMany(targetEntity="Hcp\Entity\Hcps", inversedBy="hmo")
* #ORM\JoinTable(name="hmo_hcp",
* joinColumns={#ORM\JoinColumn(name="hmo_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="hcp_id", referencedColumnName="id")}
* )
*/
protected $hcp;
public function __constructor()
{
$this->hcp = new ArrayCollection();
}
public function addHcp(Hcps $hcp)
{
// $hcp->addHmo($this); // synchronously updating inverse side
//$this->hcp[] = $hcp;
// $this->hcp->add($hcp);
//return $this->hcp;
if ($this->hcp->contains($hcp)) {
return;
}
$this->hcp->add($hcp);
$hcp->addHmo($this);
}
public function removeHcp(Hcps $hcp)
{
$this->hcp->removeElement($hcp);
return $this;
}
public function setNameofhmo($hmo)
{
$this->nameofhmo = $hmo;
return $this;
}
public function getNameofhmo()
{
return $this->nameofhmo;
}
public function setHeadoffice($headoffice)
{
$this->headoffice = $headoffice;
return $this;
}
public function getHeadoffice()
{
return $this->headoffice;
}
public function setTelno($telno)
{
$this->telno = $telno;
return $this;
}
public function getTelno()
{
return $this->telno;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
public function getEmail()
{
return $this->email;
}
public function setDoincor($doincor)
{
$this->doincor = $doincor;
return $this;
}
public function getDoincor()
{
return $this->doincor;
}
public function setRcno($rc)
{
$this->rcno = $rc;
return $this;
}
public function getRcno()
{
return $this->rcno;
}
public function setCeoname($ceo)
{
$this->ceoname = $ceo;
return $this;
}
public function getCeoname()
{
return $this->ceoname;
}
public function setBankers($bk)
{
$this->bankers = $bk;
return $this;
}
public function getBankers()
{
return $this->bankers;
}
public function setLastlogin($lastlogin)
{
$this->lastlogin = $lastlogin;
return $this;
}
public function getLastlogin()
{
return $this->lastlogin;
}
public function setRegDatetime($regdatetime)
{
$this->regdatetime = $regdatetime;
return $this;
}
public function getRegdatetime()
{
return $this->regdatetime;
}
public function setRegtime($regtime)
{
$this->regtime = $regtime;
return $this;
}
public function getRegtime()
{
return $this->regtime;
}
public function setRegdate($regdate)
{
$this->regdate = $regdate;
return $this;
}
public function getRegdate()
{
return $this->regdate;
}
public function setId($id)
{
$this->id = $id;
return $this;
//die();
}
public function getId()
{
return $this->id;
}
public function populate($data = array())
{
$this->id = $data['id'];
$this->nameofhmo = $data['nameofhmo'];
$this->headoffice = $data['headoffice'];
$this->telno = $data['telno'];
$this->email = $data['email'];
$this->doincor = $data['doincor'];
$this->rcno = $data['rcno'];
$this->ceoname = $data['ceoname'];
$this->bankers = $data['bankers'];
}
public function setHcp(Hcps $hcp = null)
{
//Hmos $hmo = null
$this->hcp = $hcp;
return $this;
}
public function getHcp()
{
return $this->hcp;
}
}
HmohcpForm.php
class HmohcpForm extends Form{
public function __construct(ObjectManager $objectManager){
parent::__construct('filmForm');
$this->setAttribute('method','post')
->setHydrator(new DoctrineHydrator($objectManager,'\Hmo\Entity\Hmos'))
->setObject(new Hmos());
$this->add(array(
'name' => 'id',
'type' => 'hidden'
));
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'hcp',
'attributes' => array(
'multiple' => 'multiple',
'class'=>'form-control',
),
'options' => array(
'object_manager' => $objectManager,
'target_class' => 'HCP\Entity\Hcps',
'property' => 'name',
'label' => 'HCP: ',
),
)
);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Add HCPs to HMO',
'id' => 'submitbutton',
'class' => 'btn btn-primary',
),
));
}
hcptohmo.php
<?php
$form = $this->form;
$form->prepare();
$form->setAttribute('action', $this->url(NULL,
array('controller'=>'Index', 'action' => 'hcptohmos','id'=> $this->id)));
$form->setAttribute('method', 'post');
?>
<?php //echo $?>
<div class="row">
<article class="contact-form col-md-8 col-sm-7 page-row">
<h3 class="title">Register HMO</h3>
<?php echo $this->form()->openTag($form); ?>
<?php echo $this->formInput($form->get('id')); ?>
<div class="form-group name">
<?php
echo $this->formElement($form->get('hcp'));
?>
</div><!--//form-group-->
<?php
echo $this->formElement($form->get('submit'));
echo $this->formElementErrors($form->get('submit'));
?>
<?php echo $this->form()->closeTag() ?>
</article><!--//contact-form-->
</div>
IndexController.php
<?php
public function hcptohmoAction()
{
$id = $this->params()->fromRoute('id');
if(!$id) {
return $this->redirect()->toRoute('admin', array(
'action' => 'index'
));
}
$hu= $this->getEntityManager()->find('Hmo\Entity\Hmos',$id);
$form = new HmohcpForm($this->getEntityManager());
$form->bind($hu);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid())
{
$form->bindValues();
$entity = $form->getData();
print_r($entity->getHcp());
}
}
return new ViewModel(array('id'=>$id,'form' => $form));
}
I thought print_r($entity->getHcp()) is supposed to return an object of selected Hcps?
i have toggled the parameter of addHcp() to an arraycollection and Hcps but still shooting same error. is something wrong with this codes pls?

you should pass an ArrayCollection to the add-methods - I think that is the problem.
Modify your add-methods to look like this:
public function addHcp(Collection $hcps)
{
foreach($hcps as $hcp) {
if( ! $this->hcp->contains($hcp)) {
$this->hcp->add($hcp);
$hcp->addHmo(new ArrayCollection(array($this));
}
}
}
Also your remove-methods (the same way):
public function removeHcp(Collection $hcps)
{
foreach($hcps as $hcp) {
$this->hcp->removeElement($hcp);
$hcp->removeHmo(new ArrayCollection(array(this)));
}
}
Doctrine also passes Collections to the add-/remove-methods, that's why it is not working

I think the problem lies in your entity methods.
I would advice to read the documentation on the Doctrine ObjectHydrator and then you will most likely find out what goes wrong.
From a quick look I would say the mistake is in the setHcp and setHmo methods. Since you have a ManyToMany association you are not supposed to use set methods in your associations at all. Check the comment at setTags here in this chapter of the documentation. You should actually only use addHcps, addHcp, removeHcp and removeHcps methods.
Collections should never be swapped.

Related

insert collection data into database

I have a CollectionType fields in my form, and I made it so I can add as many of these fields as you like, here's a pic (the collectiontype are the fields under Exception)
https://imgur.com/a/xQ7qUNT
Now I'm trying to loop through the data and insert it into an array and finally insert it into my database, but this is what I get in my databse https://imgur.com/a/WyBmmwr
also, tried getting the data that is cough after clicking submit: https://imgur.com/a/pLBKx1y and it's there.
this is my method:
/**
* #Route("/new", name="type_parking_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$typeParking = new TypeParking();
$exception = new Exception();
$form = $this->createForm(TypeParkingType::class, $typeParking);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$lesjours = $typeParking->getJourstravail();
$typeParking->getException()->add($exception);
// Here I try getting the data
$excep = $form->get('Exception');
foreach ($excep as $ExceptionForm) {
$name = $ExceptionForm->get('nom')->getData();
$StartDate = $ExceptionForm->get('datedebut')->getData();
$EndDate = $ExceptionForm->get('datefin')->getData();
$StartTime = $ExceptionForm->get('tempsdebut')->getData();
$EndTime = $ExceptionForm->get('tempsfin')->getData();
$exception->setNom($name);
$exception->setDatedebut($StartDate);
$exception->setDatefin($EndDate);
$exception->setTempsdebut($StartTime);
$exception->setTempsfin($EndTime);
$typeParking->addException($exception);
}
// ends here
// this is unrelated
$jour = $lesjours['jour'];
$debut = $lesjours['debut']->format('H:i:s');
$fin = $lesjours['fin']->format('H:i:s');
$newDate = Array('lesjour' => Array($jour => Array('heuredebut' => $debut, 'heurefin' => $fin)));
$typeParking->setJourstravail($newDate);
//end unrelated
$this->addFlash('success', "type added ");
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($typeParking);
$entityManager->flush();
return $this->redirectToRoute('type_parking_index');
}
return $this->render(
'Admin/type_parking/new.html.twig',
['type_parking' => $typeParking, 'form' => $form->createView()]
);
}
and here's my entity TypeParking
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="App\Repository\TypeParkingRepository")
*/
class TypeParking
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=55)
*/
private $libelle;
/**
* #ORM\Column(type="time", nullable=true)
*/
private $tempsmax;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $jourdebut;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $jourfin;
/**
* #ORM\Column(type="json_array", nullable=true)
*/
private $jourstravail;
/**
* #ORM\Column(type="json_array", nullable=true)
*/
private $exception;
public function __construct()
{
$this->exception = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTempsmax(): ?\DateTimeInterface
{
return $this->tempsmax;
}
public function setTempsmax(\DateTimeInterface $tempsmax): self
{
$this->tempsmax = $tempsmax;
return $this;
}
public function getJourdebut(): ?\DateTimeInterface
{
return $this->jourdebut;
}
public function setJourdebut(\DateTimeInterface $jourdebut): self
{
$this->jourdebut = $jourdebut;
return $this;
}
public function getJourfin(): ?\DateTimeInterface
{
return $this->jourfin;
}
public function setJourfin(\DateTimeInterface $jourfin): self
{
$this->jourfin = $jourfin;
return $this;
}
public function getJourstravail()
{
return array_merge([
'jour' => '',
'debut' => null,
'fin' => null,
// other sub-fields "empty" values
], $this->jourstravail ?? [] // prevent array_merge from failing if exception is empty
); }
public function setJourstravail($jourstravail): self
{
$this->jourstravail = $jourstravail;
return $this;
}
public function getException() {
return $this->exception;
}
public function setException($exception): self
{
$this->exception = $exception;
return $this;
}
public function addException($exception)
{
$this->exception->add($exception);
return $this;
}
public function getLibelle(): ?string
{
return $this->libelle;
}
public function setLibelle(string $libelle): self
{
$this->libelle = $libelle;
return $this;
}
}
btw, I have two entities, TypeParking and Exception, TypeParking has a property named Exception which is a json file type and must contain the data from Exception.

Symfony 4 multiple entities in single form

Been trying for hours and hours to get my multi entity form to work, but it really breaks my head and none of the examples I've found work.
I checked the Collection form type documentation and form collections, as well as the Entity form type.
I have a User entity, UserRole entity and a Role entity.
UserRole contains a userID and a roleID. Just a linking table.
The form shows fields to create a User and I want to be able to as well select a new Role for the new user. So I've tried to use the EntityType, a select dropdown shows with all the roles nicely (only if i add the option mapped => false), but doesn't process after form submit.
It's data is not in the $form->getData(), the user gets created, the user_role entry never created.
If I try it without the mapped => false it throws me:
Could not determine access type for property "user_roles" in class "App\Entity\User": The property "user_roles" in class "App\Entity\User" can be defined with the methods "addUserRole()", "removeUserRole()" but the new value must be an array or an instance of \Traversable, "App\Entity\Role" given..
Code:
$form = $this->createFormBuilder(new User)
... //other add entries
->add('user_roles', EntityType::class, array(
'label' => 'Group (role)',
'class' => Role::class,
'choice_label' => 'name',
// 'mapped' => false, // Form works when false, but doesn't save/create UserRole entry
))
->getForm();
$form->handleRequest($request);
Using the CollectionType it's not showing a select dropdown at all.
Code:
$form = $this->createFormBuilder($user)
.... //other add entries
->add('user_roles', CollectionType::class, array(
'entry_type' => ChoiceType::class,
'entry_options' => array(
'choices' => $roleChoices,
),
))
->getForm();
$form->handleRequest($request);
Am I missing something in my Controller's code or do I misunderstand the use of the Form types? I really have no clue what I'm doing wrong.
User Entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use JMS\Serializer\Annotation\Exclude;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
* #ORM\HasLifecycleCallbacks()
*/
class User implements UserInterface
{
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Exclude
*/
private $apiToken;
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json_array")
*/
private $roles = [];
/**
* #ORM\Column(type="string", length=255)
*/
private $first_name;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $middle_name;
/**
* #ORM\Column(type="string", length=255)
*/
private $last_name;
/**
* #ORM\Column(type="boolean")
*/
private $enabled;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $blocked_at;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Project", mappedBy="created_by")
*/
private $projects;
/**
* #ORM\OneToMany(targetEntity="App\Entity\UserRole", mappedBy="user", fetch="EAGER")
*/
private $user_roles;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Category", mappedBy="created_by")
*/
private $categories;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ProjectFileIos", mappedBy="created_by")
*/
private $projectFileIos;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ProjectFileAndroid", mappedBy="created_by")
*/
private $projectFileAndroid;
/**
* Generate full name
*/
private $full_name;
/**
* #var string The hashed password
* #ORM\Column(type="string")
* #Exclude
*/
private $password;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ProjectUser", mappedBy="user", fetch="EAGER")
*/
private $projectUsers;
/**
* #ORM\Column(type="datetime")
*/
private $created_at;
/**
* #ORM\Column(type="datetime")
*/
private $updated_at;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="project")
*/
private $created_by;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="project")
* #ORM\JoinColumn(nullable=true)
*/
private $last_updated_by;
public function __construct()
{
$this->user_roles = new ArrayCollection();
$this->user_role = new ArrayCollection();
$this->categories = new ArrayCollection();
$this->projectFileIos = new ArrayCollection();
$this->projectFileAndroid = new ArrayCollection();
$this->projectUsers = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getApiToken(): ?string
{
return $this->apiToken;
}
public function setApiToken(string $apiToken): self
{
$this->apiToken = $apiToken;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getFirstName(): ?string
{
return $this->first_name;
}
public function setFirstName(string $first_name): self
{
$this->first_name = $first_name;
return $this;
}
public function getMiddleName(): ?string
{
return $this->middle_name;
}
public function setMiddleName(string $middle_name): self
{
$this->middle_name = $middle_name;
return $this;
}
public function getLastName(): ?string
{
return $this->last_name;
}
public function setLastName(string $last_name): self
{
$this->last_name = $last_name;
return $this;
}
public function getEnabled(): ?bool
{
return $this->enabled;
}
public function setEnabled(bool $enabled): self
{
$this->enabled = $enabled;
return $this;
}
public function getBlockedAt(): ?\DateTimeInterface
{
return $this->blocked_at;
}
public function setBlockedAt(?\DateTimeInterface $blocked_at): self
{
$this->blocked_at = $blocked_at;
return $this;
}
/**
* #return Collection|UserRole[]
*/
public function getUserRoles(): ?Collection
{
return $this->user_roles;
}
public function getUserRole(): ?Collection
{
return $this->user_role;
}
public function addUserRole(UserRole $userRole): self
{
if (!$this->user_role->contains($userRole)) {
$this->user_role[] = $userRole;
$user_role->setUserId($this);
}
return $this;
}
public function removeUserRole(UserRole $userRole): self
{
if ($this->user_role->contains($userRole)) {
$this->user_role->removeElement($userRole);
// set the owning side to null (unless already changed)
if ($user_role->getUserId() === $this) {
$user_role->setUserId(null);
}
}
return $this;
}
/**
* #return Collection|Project[]
*/
public function getProjects(): Collection
{
return $this->projects;
}
public function addProject(Project $project): self
{
if (!$this->project->contains($project)) {
$this->project[] = $project;
$project->setUserId($this);
}
return $this;
}
public function removeProject(Project $project): self
{
if ($this->project->contains($project)) {
$this->project->removeElement($project);
// set the owning side to null (unless already changed)
if ($project->getUserId() === $this) {
$project->setUserId(null);
}
}
return $this;
}
/**
* #return Collection|Category[]
*/
public function getCategories(): Collection
{
return $this->categories;
}
public function addCategory(Category $category): self
{
if (!$this->categories->contains($category)) {
$this->categories[] = $category;
$category->setCreatedBy($this);
}
return $this;
}
public function removeCategory(Category $category): self
{
if ($this->categories->contains($category)) {
$this->categories->removeElement($category);
// set the owning side to null (unless already changed)
if ($category->getCreatedBy() === $this) {
$category->setCreatedBy(null);
}
}
return $this;
}
/**
* #return Collection|ProjectFileIos[]
*/
public function getProjectFileIos(): Collection
{
return $this->projectFileIos;
}
public function addProjectFileIo(ProjectFileIos $projectFileIo): self
{
if (!$this->projectFileIos->contains($projectFileIo)) {
$this->projectFileIos[] = $projectFileIo;
$projectFileIo->setCreatedBy($this);
}
return $this;
}
public function removeProjectFileIo(ProjectFileIos $projectFileIo): self
{
if ($this->projectFileIos->contains($projectFileIo)) {
$this->projectFileIos->removeElement($projectFileIo);
// set the owning side to null (unless already changed)
if ($projectFileIo->getCreatedBy() === $this) {
$projectFileIo->setCreatedBy(null);
}
}
return $this;
}
/**
* #return Collection|ProjectFileAndroid[]
*/
public function getProjectFileAndroid(): Collection
{
return $this->projectFileAndroid;
}
public function addProjectFileAndroid(ProjectFileAndroid $projectFileAndroid): self
{
if (!$this->projectFileAndroid->contains($projectFileAndroid)) {
$this->projectFileAndroid[] = $projectFileAndroid;
$projectFileAndroid->setCreatedBy($this);
}
return $this;
}
public function removeProjectFileAndroid(ProjectFileAndroid $projectFileAndroid): self
{
if ($this->projectFileAndroid->contains($projectFileAndroid)) {
$this->projectFileAndroid->removeElement($projectFileAndroid);
// set the owning side to null (unless already changed)
if ($projectFileAndroid->getCreatedBy() === $this) {
$projectFileAndroid->setCreatedBy(null);
}
}
return $this;
}
public function getFullName()
{
$lastName = $this->middle_name ? $this->middle_name . ' ' : '';
$lastName .= $this->last_name;
return $this->first_name . ' ' . $lastName;
}
/**
* Triggered after entity has been loaded into the current EntityManager from de database
* or after refresh operation applied to it
* #ORM\PostLoad
*/
public function postLoad()
{
$this->full_name = $this->getFullName();
}
/**
* #return Collection|ProjectUser[]
*/
public function getProjectUsers(): Collection
{
return $this->projectUsers;
}
public function addProjectUser(ProjectUser $projectUser): self
{
if (!$this->projectUsers->contains($projectUser)) {
$this->projectUsers[] = $projectUser;
$projectUser->setUser($this);
}
return $this;
}
public function removeProjectUser(ProjectUser $projectUser): self
{
if ($this->projectUsers->contains($projectUser)) {
$this->projectUsers->removeElement($projectUser);
// set the owning side to null (unless already changed)
if ($projectUser->getUser() === $this) {
$projectUser->setUser(null);
}
}
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updated_at;
}
public function setUpdatedAt(\DateTimeInterface $updated_at): self
{
$this->updated_at = $updated_at;
return $this;
}
public function getCreatedBy(): ?User
{
return $this->created_by;
}
public function setCreatedBy(?User $created_by): self
{
$this->created_by = $created_by;
return $this;
}
public function getLastUpdatedBy(): ?User
{
return $this->last_updated_by;
}
public function setLastUpdatedBy(?User $last_updated_by): self
{
$this->last_updated_by = $last_updated_by;
return $this;
}
/**
* Triggered on insert
* #ORM\PrePersist
*/
public function onPrePersist()
{
$this->enabled = true;
$this->created_at = new \DateTime("now");
$this->updated_at = new \DateTime();
$this->roles = 'a:1:{i:0;s:9:"ROLE_USER";}';
}
/**
* Triggered on update
* #ORM\PreUpdate
*/
public function onPreUpdate()
{
$this->updated_at = new \DateTime("now");
}
}
In Symfony, to get non-mapped form data, try doing like this.
$data = $form->getData();
$roles = $form->get("user_roles")->getData();
Also, noted one thing. Shouldn't the class be UserRole::class instead of Role::class, in the code block below.
$form = $this->createFormBuilder(new User)
... //other add entries
->add('user_roles', EntityType::class, array(
'label' => 'Group (role)',
'class' => Role::class,
'choice_label' => 'name',
// 'mapped' => false, // Form works when false, but doesn't save/create UserRole entry
))
->getForm();
Hope this helps,
Cheers..
The general way you have chosen is okay. Stick with the EntityType and remove the mapped = false, this would tell Symfony to ignore the field.
I guess the problem is: you have a mixture of $this->user_role and $this->user_roles in your class, probably a renamed variable. Clean this up first in __construct(), addUserRole(), removeUserRole(), getUserRoles(), getUserRole().
Then add a method
public function setUserRoles($userRoles)
{
$this->user_roles = new ArrayCollection();
foreach ($userRoles as $role) {
$this->addUserRole($role);
}
return $this;
}

exist and have public access in class "Symfony\Component\Form\FormView". Symfony 4

I've a problem about datas on my form view
The principle is the same as this video (https://www.youtube.com/watch?v=MRfsHix1eRA&t=1257s), that is to say: when I select a "management" I want the "services" associated to this "management".
These must be selected in a "report Form" (Report Entity).
OneOrMany service is linked to One management, and a report is linked to a management and a service.
Entities
Management.php
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\ManagementRepository")
*/
class Management
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Service", mappedBy="management")
*/
private $services;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Report", mappedBy="management")
*/
private $reports;
public function __construct()
{
$this->services = new ArrayCollection();
$this->reports = new ArrayCollection();
}
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;
}
/**
* #return Collection|Service[]
*/
public function getServices(): Collection
{
return $this->services;
}
public function addService(Service $service): self
{
if (!$this->services->contains($service)) {
$this->services[] = $service;
$service->setManagement($this);
}
return $this;
}
public function removeService(Service $service): self
{
if ($this->services->contains($service)) {
$this->services->removeElement($service);
// set the owning side to null (unless already changed)
if ($service->getManagement() === $this) {
$service->setManagement(null);
}
}
return $this;
}
/**
* #return Collection|Report[]
*/
public function getReports(): Collection
{
return $this->reports;
}
public function addReport(Report $report): self
{
if (!$this->reports->contains($report)) {
$this->reports[] = $report;
$report->setManagement($this);
}
return $this;
}
public function removeReport(Report $report): self
{
if ($this->reports->contains($report)) {
$this->reports->removeElement($report);
// set the owning side to null (unless already changed)
if ($report->getManagement() === $this) {
$report->setManagement(null);
}
}
return $this;
}
}
Service.php
<?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\ReportRepository")
*/
class Report
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="date")
*/
private $assigned_date;
/**
* #ORM\Column(type="decimal", precision=7, scale=2, nullable=true)
*/
private $time;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Game", inversedBy="reports")
*/
private $game;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Management", inversedBy="reports")
*/
private $management;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Service", inversedBy="reports")
*/
private $service;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Format", inversedBy="reports")
*/
private $format;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="reports")
* #ORM\JoinColumn(nullable=false)
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="reports")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
public function getId(): ?int
{
return $this->id;
}
public function getAssignedDate(): ?\DateTimeInterface
{
return $this->assigned_date;
}
public function setAssignedDate(\DateTimeInterface $assigned_date): self
{
$this->assigned_date = $assigned_date;
return $this;
}
public function getTime()
{
return $this->time;
}
public function setTime($time): self
{
$this->time = $time;
return $this;
}
public function getGame(): ?Game
{
return $this->game;
}
public function setGame(?Game $game): self
{
$this->game = $game;
return $this;
}
public function getManagement(): ?Management
{
return $this->management;
}
public function setManagement(?Management $management): self
{
$this->management = $management;
return $this;
}
public function getService(): ?Service
{
return $this->service;
}
public function setService(?Service $service): self
{
$this->service = $service;
return $this;
}
public function getFormat(): ?Format
{
return $this->format;
}
public function setFormat(?Format $format): self
{
$this->format = $format;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
Report.php
<?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\ReportRepository")
*/
class Report
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="date")
*/
private $assigned_date;
/**
* #ORM\Column(type="decimal", precision=7, scale=2, nullable=true)
*/
private $time;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Game", inversedBy="reports")
*/
private $game;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Management", inversedBy="reports")
*/
private $management;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Service", inversedBy="reports")
*/
private $service;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Format", inversedBy="reports")
*/
private $format;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="reports")
* #ORM\JoinColumn(nullable=false)
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="reports")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
public function getId(): ?int
{
return $this->id;
}
public function getAssignedDate(): ?\DateTimeInterface
{
return $this->assigned_date;
}
public function setAssignedDate(\DateTimeInterface $assigned_date): self
{
$this->assigned_date = $assigned_date;
return $this;
}
public function getTime()
{
return $this->time;
}
public function setTime($time): self
{
$this->time = $time;
return $this;
}
public function getGame(): ?Game
{
return $this->game;
}
public function setGame(?Game $game): self
{
$this->game = $game;
return $this;
}
public function getManagement(): ?Management
{
return $this->management;
}
public function setManagement(?Management $management): self
{
$this->management = $management;
return $this;
}
public function getService(): ?Service
{
return $this->service;
}
public function setService(?Service $service): self
{
$this->service = $service;
return $this;
}
public function getFormat(): ?Format
{
return $this->format;
}
public function setFormat(?Format $format): self
{
$this->format = $format;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
FormType
ReportType.php
<?php
namespace App\Form;
use App\Entity\Report;
use App\Entity\Game;
use App\Entity\Management;
use App\Entity\Service;
use App\Entity\Format;
use App\Entity\Category;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
class ReportType extends AbstractType
{
protected $tokenStorage;
public function __construct(TokenStorage $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->tokenStorage->getToken()->getUser();
$builder->add('assigned_date', DateType::class, array(
'widget' => 'single_text',
// prevents rendering it as type="date", to avoid HTML5 date pickers
'html5' => false,
// adds a class that can be selected in JavaScript
'attr' => ['class' => 'js-datepicker'],
));
$builder->add('time');
$builder->add('game', EntityType::class, array(
'class' => Game::class,
'placeholder' => '',
'choice_label' => 'name'));
$builder->add('management', EntityType::class, array(
'class' => Management::class,
'placeholder' => 'Select a management',
'mapped' => false,
'choice_label' => 'name'));
$builder->get('management')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event)
{
$form = $event->getForm();
$form->getParent()->add('service',EntityType::class, array(
'class' => Service::class,
'placeholder' => 'Select a service',
'choices' => $form->getData()->getServices()
));
}
);
$builder->add('format', EntityType::class, array(
'class' => Format::class,
'placeholder' => '',
'choice_label' => 'name'));
$builder->add('category', EntityType::class, array(
'class' => Category::class,
'placeholder' => '',
'choice_label' => 'name'));
$builder->add('user', EntityType::class, array(
'class' => User::class,
'query_builder' => function (EntityRepository $er) {
$user = $this->tokenStorage->getToken()->getUser();
return $er->createQueryBuilder('u')
->Where('u.id='. $user->getId());
},
'choice_label' => 'id',
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Report::class,
]);
}
}
Twig associated
_form.twig.php
<?php
namespace App\Controller;
use App\Entity\Report;
use App\Form\ReportType;
use App\Repository\ReportRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* #Route("/report")
*/
class ReportController extends AbstractController
{
/**
* #Route("/", name="report_index", methods="GET")
*/
public function index(ReportRepository $reportRepository): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser()->getId();
return $this->render('report/index.html.twig', ['reports' => $reportRepository->findAllByIdUser($user)]);
}
/**
* #Route("/new", name="report_new", methods="GET|POST")
*/
public function new(Request $request): Response
{
$report = new Report();
$form = $this->createForm(ReportType::class, $report);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($report);
$em->flush();
return $this->redirectToRoute('report_index');
}
return $this->render('report/new.html.twig', [
'report' => $report,
'form' => $form->createView(),
]);
}
/**
* #Route("/{id}", name="report_show", methods="GET")
*/
public function show(Report $report): Response
{
return $this->render('report/show.html.twig', ['report' => $report]);
}
/**
* #Route("/{id}/edit", name="report_edit", methods="GET|POST")
*/
public function edit(Request $request, Report $report): Response
{
$form = $this->createForm(ReportType::class, $report);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('report_edit', ['id' => $report->getId()]);
}
return $this->render('report/edit.html.twig', [
'report' => $report,
'form' => $form->createView(),
]);
}
/**
* #Route("/{id}", name="report_delete", methods="DELETE")
*/
public function delete(Request $request, Report $report): Response
{
if ($this->isCsrfTokenValid('delete'.$report->getId(), $request->request->get('_token'))) {
$em = $this->getDoctrine()->getManager();
$em->remove($report);
$em->flush();
}
return $this->redirectToRoute('report_index');
}
}
When I dump() my $form->getData()->getServices(), this return a collection. but i've this message : Neither the property "service" nor one of the methods "service()", "getservice()"/"isservice()"/"hasservice()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
on {{ form_widget(form.service, { 'attr': {'placeholder': "Service"} }) }}
Some people have a solution ?
I can provide more information if you need it
Thank you.

Doctrine arraycollection keeps being null

Hey Im just trying out doctrine for php alittle and i got an issue with my $matches arraycollection, when i set it in the __construct it works but afterwards its just null and i cant seem to figure out why, the other arraycollections works perfectly
<?php
// src/Player.php
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity #Table(name="teams")
**/
class Team
{
/**
* #Id #Column(type="integer") #GeneratedValue
**/
protected $id;
/**
* #Column(type="string")
**/
protected $name;
/**
* #OneToMany(targetEntity="Player", mappedBy="team")
**/
protected $players;
/**
* #OneToMany(targetEntity="Goal",mappedBy="againstTeam")
**/
protected $goalsAgainst;
/**
* #Column(type="string")
**/
protected $color;
/**
* ManyToMany(targetEntity="Match", mappedBy="teams")
**/
protected $matches;
public function __construct()
{
$this->matches = new ArrayCollection();
$this->players = new ArrayCollection();
$this->goalsAgainst = new ArrayCollection();
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
public function getMatches() {
return $this->matches;
}
public function addMatch(Match $match) {
$this->matches->add($match);
}
public function setName($name) {
$this->name = $name;
}
public function setColor($color) {
$this->color = $color;
}
public function addGoalsAgainst(Goal $goal) {
$this->goalsAgainst->add($goal);
$goal->setAgainstTeam($this);
}
public function getJson() {
return array(
'Id'=>$this->id,
'Name'=>$this->name,
'Players'=>null,
'GoalsAgainst'=>null,
'Color'=>$this->color,
'Matches'=>null
);
}
}
?>
if i add an nullcheck to the addMatches(Match $match) like
public function addMatch(Match $match) {
if ($this->matches == null) {
$this->matches = new ArrayCollection();
}
$this->matches->add($match);
}
then the match is added but if i then at next line uses $team->getMatches() then the $matches is null again

Doctrine entity not setting parameters when persisting data

I'm trying to save some data using Doctrine using entities. I've got it reading data in various ways perfectly fine, including associations etc, but I can't seem to get it to save data.
I have the following entity:
<?php
namespace CommentsBundle\Entities;
use Doctrine\ORM\Mapping AS ORM;
/**
* #Entity
* #Table(name="comments")
*/
class Comments
{
/**
* #Column(type="integer")
* #Id
* #GeneratedValue(strategy="AUTO")
*/
private $id;
/** #Column(type="string") */
protected $name;
/** #Column(type="string") */
protected $email;
/** #Column(type="string") */
protected $content;
/** #Column(type="string") */
protected $date;
/** #Column(type="integer") */
protected $user_id;
/** #Column(type="integer") */
protected $post_id;
/** #ManyToOne(targetEntity="UserBundle\Entities\Users") */
protected $user;
/** #ManyToOne(targetEntity="ContentBundle\Entities\Posts") */
protected $post;
public function setId( $id )
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setName( $name )
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setEmail( $email )
{
$this->email = $email;
}
public function getEmail()
{
return $this->email;
}
public function setContent( $content )
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setDate( $date )
{
$this->date = $date;
}
public function getDate()
{
return $this->date;
}
public function setUser_id( $user_id )
{
$this->user_id = $user_id;
}
public function getUser_id()
{
return $this->user_id;
}
public function setPost_id( $post_id )
{
$this->post_id = $post_id;
}
public function getPost_id()
{
return $this->post_id;
}
}
And I have the following method in my controller:
public function newComment( Request $request )
{
$this->model->setDate = new \DateTime();
$this->model->setName = $request->get( 'name' );
$this->model->setEmail = $request->get( 'email' );
$this->model->setContent = $request->get( 'content' );
$this->model->setPost_id = $request->get( 'id' );
$this->model->setUser_id = $request->get( 1 );
self::$app['orm.em']->persist( $this->model );
self::$app['orm.em']->flush();
if ( $save ) {
de( 'Worked' );
} else {
de( 'Did not work' );
}
}
I get an error in my error log saying all the values are set to null... if I set the entities parameters to public and set them like $this->model->name = 'A name'; etc, that works, but obviously this isn't best practice.
If I var_dump $this->model it shows that the setter methods all have the correct values, but the parameters are all set to null.
Does anyone know why my setters aren't working?
Cheers,
Ewan
Proper use of setters is $this->model->setDate(new DateTime()); not $this->model->setDate =...
You missed ORM\ prefix in annotations:
/**
* #ORM\Entity
* #ORM\Table(name="comments")
*/
class Comments
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/** #ORM\Column(type="string") */
protected $name;
/** #ORM\Column(type="string") */
protected $email;
/** #ORM\Column(type="string") */
protected $content;
/** #ORM\Column(type="string") */
protected $date;
/** #ORM\Column(type="integer") */
protected $user_id;
/** #ORM\Column(type="integer") */
protected $post_id;
/** #ORM\ManyToOne(targetEntity="UserBundle\Entities\Users") */
protected $user;
/** #ORM\ManyToOne(targetEntity="ContentBundle\Entities\Posts") */
protected $post;
public function setId( $id )
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setName( $name )
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setEmail( $email )
{
$this->email = $email;
}
public function getEmail()
{
return $this->email;
}
public function setContent( $content )
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setDate( $date )
{
$this->date = $date;
}
public function getDate()
{
return $this->date;
}
public function setUser_id( $user_id )
{
$this->user_id = $user_id;
}
public function getUser_id()
{
return $this->user_id;
}
public function setPost_id( $post_id )
{
$this->post_id = $post_id;
}
public function getPost_id()
{
return $this->post_id;
}
}
and then in action:
public function newComment( Request $request )
{
$this->model->setDate( new \DateTime() );
$this->model->setName( $request->get( 'name' ) );
$this->model->setEmail( $request->get( 'email' ) );
$this->model->setContent( $request->get( 'content' ) );
$this->model->setPost_id( $request->get( 'id' ) );
$this->model->setUser_id( $request->get( 1 ) );
self::$app['orm.em']->persist( $this->model );
self::$app['orm.em']->flush();
if ( $save ) {
de( 'Worked' );
} else {
de( 'Did not work' );
}
}
Also will be useful Add Mapping Information

Categories