php doctrine orm cant insert joinColumn null - php

first at all thanks for reading.
I'm a little bit new with Doctrine Orm. My problem is that i have declared a class that has two oneToMany joinColumns, but i need to insert data even when i do not have those joinColumn data.
So, i have a var with three possible values, "factura" | "nota credito" | "nota debito". When "factura" is choosen then i have to add two arrayCollection() to add possible data. But when "nota credito" or "nota debito" choosen i dont have to add the arrays, but when that happends... the new factura object did not insert.
So here is my code of the Librarie and modelCode. Please see just the _construct and the last two joinColumns mapped.
public function insertaFactura($information) {
$cliente = $this->getCollectionByid("Cliente", $information['cob_cliente']);
$factura = new Factura($information, $cliente);
$this->orm->flush();
$this->orm->persist($factura);
if ($information['doc_tipo'] == "factura") {
if ($information['articulos']) {
foreach ($information['articulos'] as $key_venta => $articulos) {
foreach ($articulos as $articulo) {
$ventaArticulo = $this->getCollectionByid("Venta_Articulo", $articulo);
$fva = new Factura_Venta_Articulo();
$fva->setVentaArticulo($ventaArticulo);
$fva->setFactura($factura);
$this->orm->persist($fva);
}
}
$this->orm->flush();
}
}
return $factura->getId();
}
<?php
use \Doctrine\Common\Collections\ArrayCollection;
/**
* Factura
*
* #Table(name="documento_cliente")
* #Entity
*/
class Factura {
/**
* #var integer $id
*
* #Column(name="doc_id", type="integer", nullable=false)
* #Id
* #GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $numero
*
* #Column(name="doc_numero", type="string", length=120, nullable=true)
*/
private $numero;
/**
* #var string $tipo
*
* #Column(name="doc_tipo", type="string")
*/
private $tipo;
/**
* #var string $fecha
*
* #Column(name="doc_fecha", type="date", length=1, nullable=true)
*/
private $fecha;
/**
* #var integer $estado
*
* #Column(name="doc_estado", type="integer", length=120, nullable=true)
*/
private $estado;
/**
* #OneToOne(targetEntity="Cliente", cascade={"persist", "remove"}))
* #JoinColumn(name="doc_cliente_id", referencedColumnName="cli_id")
* */
private $cliente;
/**
* #OneToMany(targetEntity="Factura_Venta_Articulo", mappedBy="factura")
* #JoinColumn(name="fva_ver_id", referencedColumnName="ver_id",nullable=true)
* */
private $venta_articulo;
/**
* #OneToMany(targetEntity="Cobro_factura", mappedBy="factura")
* #JoinColumn(name="cof_id", referencedColumnName="cobro_id",nullable=true)
* */
private $cobros;
public function getId() {
return $this->id;
}
public function getTipo() {
return $this->tipo;
}
public function getNumero() {
return $this->numero;
}
public function getFecha() {
return $this->fecha;
}
public function getEstado() {
return $this->estado;
}
public function getCliente() {
return $this->cliente;
}
public function getVentasArticulo() {
return $this->venta_articulo;
}
public function getCobros() {
return $this->cobros;
}
public function setNumero($numero) {
$this->numero = $numero;
}
public function setTipo($tipo) {
$this->tipo = $tipo;
}
public function setFecha($fecha) {
$this->fecha = $fecha;
}
public function setEstado($estado) {
$this->estado = $estado;
}
public function setCliente($cliente) {
$this->cliente = $cliente;
}
public function __construct($parameters, $cliente) {
$this->setEstado(3);
$this->setFecha(new \DateTime($parameters['factura_fecha']));
$this->setNumero($parameters['factura_numero']);
$this->setCliente($cliente);
$this->setTipo($parameters['doc_tipo']);
if ($parameters['doc_tipo'] == 'factura') {
$this->venta_articulo = new ArrayCollection();
$this->cobros = new ArrayCollection();
}
}
public function actualizar($numero, $fecha, $cliente) {
$this->setNumero($numero);
$this->setFecha(new \DateTime($fecha));
$this->setCliente($cliente);
}
public function totalFactura() {
$total = 0.0;
foreach ($this->venta_articulo as $ventaArticulo) {
$total+=$ventaArticulo->getVentaArticulo()->getIngreso();
}
return $total;
}
public function totalFacturaCobrado() {
$total = 0;
foreach ($this->cobros as $cobro) {
$total+=$cobro->getCobranza();
}
return number_format($total, 2, '.', '');
}
public function totalFacturaACobrar() {
return number_format($this->totalFactura(), 2, '.', '') - number_format($this->totalFacturaCobrado(), 2, '.', '');
}
}

Related

Symfony 4 Add ManyToMany Entity trough FORM

I am heavily stuck on problem with inserting data trough html.twig when passing one Entity to the other. I am able to add or edit single entities but i cant figure out how to handle adding relations.
Tournament Entity class - unimportant stuff deleted
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Tournament.
*
* #ORM\Table(name="tournament")
* #ORM\Entity(repositoryClass="App\Repository\TournamentRepository")
*/
class Tournament
{
/**
* #var int
*
* #ORM\Column(name="id_tournament", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idTournament;
/**
* #var string
*
* #ORM\Column(name="name_of_event", type="string", length=128, nullable=false)
*/
private $nameOfEvent;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=16, nullable=false)
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="prizepool", type="string", length=32, nullable=false)
*/
private $prizepool;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=128, nullable=false)
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=32, nullable=false)
*/
private $country;
/**
* #var \DateTime
*
* #ORM\Column(name="start_date", type="date", nullable=false)
*/
private $startDate;
/**
* #var \DateTime
*
* #ORM\Column(name="end_date", type="date", nullable=false)
*/
private $endDate;
/**
* #var string|null
*
* #ORM\Column(name="tournament_Img", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $tournamentImg = 'NULL';
/**
* #ORM\OneToMany(targetEntity="App\Entity\Eventstandings", mappedBy="tourn")
*/
private $events;
/**
* #ORM\OneToMany(targetEntity=Comment::class, mappedBy="tourn_id")
*/
private $comments;
/**
* #ORM\ManyToMany(targetEntity=Team::class, inversedBy="tournaments")
* #ORM\JoinTable(name="playedAt", joinColumns={#ORM\JoinColumn(name="tourn_id", referencedColumnName="id_tournament")},
* inverseJoinColumns={#ORM\JoinColumn(name="team_id", referencedColumnName="ID_Team")})
*/
private $teams;
/**
* #return ArrayCollection
*/
public function getEvents(): Collection
{
return $this->events;
}
/**
* #param ArrayCollection $events
*/
public function setEvents(Collection $events): void
{
$this->events = $events;
}
public function __construct()
{
$this->teams = new ArrayCollection();
$this->events = new ArrayCollection();
$this->comments = new ArrayCollection();
}
public function getIdTournament(): ?int
{
return $this->idTournament;
}
public function addTeam(Team $team): self
{
if (!$this->teams->contains($team)) {
$this->teams[] = $team;
}
return $this;
}
public function removeTeam(Team $team): self
{
if ($this->teams->contains($team)) {
$this->teams->removeElement($team);
}
return $this;
}
}
Team Entity class
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
/**
* Team.
*
* #ORM\Table(name="team")
* #ORM\Entity(repositoryClass="App\Repository\TeamRepository")
*/
class Team
{
/**
* #var int
*
* #ORM\Column(name="ID_Team", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idTeam;
/**
* #var string
*
* #ORM\Column(name="Name", type="string", length=128, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="Region", type="text", length=65535, nullable=false)
*/
private $region;
/**
* #var string
*
* #ORM\Column(name="Coach", type="string", length=64, nullable=false)
*/
private $coach;
/**
* #var string
*
* #ORM\Column(name="Total_Earnings", type="string", length=64, nullable=false)
*/
private $totalEarnings;
/**
* #var string|null
*
* #ORM\Column(name="img_Path", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $imgPath = 'NULL';
/**
* #ORM\OneToMany(targetEntity=Player::class, mappedBy="team", cascade={"persist","remove"})
*/
private $ownedPlayers;
/**
* #var string|null
*
* #ORM\Column(name="player_Img", type="string", length=64, nullable=true, options={"default"="NULL"})
*/
private $playerImg = 'NULL';
/**
* #ORM\OneToMany(targetEntity="App\Entity\Eventstandings", mappedBy="team")
*/
private $playedEventAsoc;
/**
* #ORM\ManyToMany(targetEntity=Tournament::class, mappedBy="teams")
*/
private $tournaments;
public function getIdTeam(): ?int
{
return $this->idTeam;
}
public function __construct()
{
$this->tournaments = new ArrayCollection();
$this->playedEventAsoc = new ArrayCollection();
$this->ownedPlayers = new ArrayCollection();
}
public function getPlayedEventAsoc(): Collection
{
return $this->playedEventAsoc;
}
public function setPlayedEventAsoc(Collection $playedEventAsoc): void
{
$this->playedEventAsoc = $playedEventAsoc;
}
public function getStandings(): void
{
$standings = getPlayedEventAsoc().$this->getStandings();
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getRegion(): ?string
{
return $this->region;
}
public function setRegion(string $region): self
{
$this->region = $region;
return $this;
}
public function getCoach(): ?string
{
return $this->coach;
}
public function setCoach(string $coach): self
{
$this->coach = $coach;
return $this;
}
public function getTotalEarnings(): ?string
{
return $this->totalEarnings;
}
public function setTotalEarnings(string $totalEarnings): self
{
$this->totalEarnings = $totalEarnings;
return $this;
}
public function getImgPath(): ?string
{
return $this->imgPath;
}
public function setImgPath(?string $imgPath): self
{
$this->imgPath = $imgPath;
return $this;
}
public function getPlayerImg(): ?string
{
return $this->playerImg;
}
public function setPlayerImg(?string $playerImg): self
{
$this->playerImg = $playerImg;
return $this;
}
public function addPlayer(Player $player): self
{
if (!$this->ownedPlayers->contains($player)) {
$this->ownedPlayers[] = $player;
$player->setTeam($this);
}
return $this;
}
public function removePlayer(Player $player): self
{
if ($this->ownedPlayers->contains($player)) {
$this->ownedPlayers->removeElement($player);
// set the owning side to null (unless already changed)
if ($player->getTeam() === $this) {
$player->setTeam(null);
}
}
return $this;
}
/**
* #return Collection|Player[]
*/
public function getOwnedPlayers(): Collection
{
return $this->ownedPlayers;
}
public function addOwnedPlayer(Player $ownedPlayer): self
{
if (!$this->ownedPlayers->contains($ownedPlayer)) {
$this->ownedPlayers[] = $ownedPlayer;
$ownedPlayer->setTeam($this);
}
return $this;
}
public function removeOwnedPlayer(Player $ownedPlayer): self
{
if ($this->ownedPlayers->contains($ownedPlayer)) {
$this->ownedPlayers->removeElement($ownedPlayer);
// set the owning side to null (unless already changed)
if ($ownedPlayer->getTeam() === $this) {
$ownedPlayer->setTeam(null);
}
}
return $this;
}
public function addEvents(Eventstandings $event): self
{
if (!$this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc[] = $event;
$event->setTeam($this);
}
return $this;
}
public function removeEvents(Eventstandings $event): self
{
if ($this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc->removeElement($event);
// set the owning side to null (unless already changed)
if ($event->getTeam() === $this) {
$event->setTeam(null);
}
}
return $this;
}
public function addEvent(Eventstandings $event): self
{
if (!$this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc[] = $event;
$event->setTeam($this);
}
return $this;
}
public function removeEvent(Eventstandings $event): self
{
if ($this->playedEventAsoc->contains($event)) {
$this->playedEventAsoc->removeElement($event);
// set the owning side to null (unless already changed)
if ($event->getTeam() === $this) {
$event->setTeam(null);
}
}
return $this;
}
public function getEventData(PersistentCollection $playedEvents): array
{
$eventdata = $playedEvents->getValues();
return $eventdata;
}
public function addPlayedEventAsoc(Eventstandings $playedEventAsoc): self
{
if (!$this->playedEventAsoc->contains($playedEventAsoc)) {
$this->playedEventAsoc[] = $playedEventAsoc;
$playedEventAsoc->setTeam($this);
}
return $this;
}
public function removePlayedEventAsoc(Eventstandings $playedEventAsoc): self
{
if ($this->playedEventAsoc->contains($playedEventAsoc)) {
$this->playedEventAsoc->removeElement($playedEventAsoc);
// set the owning side to null (unless already changed)
if ($playedEventAsoc->getTeam() === $this) {
$playedEventAsoc->setTeam(null);
}
}
return $this;
}
/**
* #return Collection|Tournament[]
*/
public function getTournaments(): Collection
{
return $this->tournaments;
}
public function addTournament(Tournament $tournament): self
{
if (!$this->tournaments->contains($tournament)) {
$this->tournaments[] = $tournament;
$tournament->addTeam($this);
}
return $this;
}
public function removeTournament(Tournament $tournament): self
{
if ($this->tournaments->contains($tournament)) {
$this->tournaments->removeElement($tournament);
$tournament->removeTeam($this);
}
return $this;
}
}
I am able to edit tournament or team data trough forms and save it to database.
What I am not able is to add data into this relation.
Form Class for this
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('team', EntityType::class, array(
'class' => Team::class,
'multiple' => true,
'expanded' => true,
))
->add('Add Team', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Tournament::class
]);
}
Tournament Controller method addTeam - should add Team Entity into Trounament teams collection
/**
* #param Team $team
* #param Request $request
* #Route("/addTeamToEvent/{idTournament}",name="addTeamToEvent")
* #return RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function addTeam(Tournament $tournament, Request $request)
{
$form = $this->createForm(TeamToEvent::class, $tournament);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->persist($tournament);
$this->entityManager->flush();
return new RedirectResponse($this->router->generate('welcome'));
}
return $this->render('welcome/addTeamToEvent.html.twig', ['form' => $form->createView()]);
}
What should be the right aproach? I am totaly lost and i don't know how to do this.

Doctrine entity always saves null on persist even when set

I'm trying to persist some data to the database but even though I'm setting a field it sets it to null when the actual SQL runs. The field is set to not null in the database which throws an error.
My code:
$db_order = new Orders;
$db_order->setDateCreated(new \DateTime());
$db_order->setLastUpdated(null);
$db_order->setDateAssigned(null);
$db_order->setCreatedBy($user->getId());
$db_order->setAttachmentId($order->getFaxId());
$db_order->setPatientId($order->getPatientId());
$db_order->setPaymentType($order->getPaymentType());
$db_order->setInsuranceName($order->getInsuranceName());
$db_order->setInsuranceNo($order->getInsuranceNo());
$db_order->setCash($order->getCash());
$db_order->setPrimaryClientId($order->getPrimaryClient());
$db_order->setSecondaryClients($secondaryClients);
$db_order->setEmployees($employees);
$db_order->setDates($dates);
$db_order->setNotes($note);
dump($db_order->getPatientId());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($db_order);
$entityManager->flush();
I was double checking with that dump before the persist and it has the field set correctly. Yet when the page runs...
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'patient_id' cannot be null
I don't understand how it could be null? Any ideas?
Orders Entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\GroupSequenceProviderInterface;
/**
* #ORM\Entity(repositoryClass="App\Repository\OrdersRepository")
* #Assert\GroupSequenceProvider()
*/
class Orders implements GroupSequenceProviderInterface
{
const TYPE_InsuranceOnly = 1;
const TYPE_InsuranceAndCash = 2;
const TYPE_CashOnly = 3;
/**
* #ORM\ManyToOne(targetEntity="Patients")
* #ORM\JoinColumn(name="patient_id", referencedColumnName="id")
*/
private $patients;
/**
* #ORM\ManyToOne(targetEntity="Clients")
* #ORM\JoinColumn(name="primary_client_id", referencedColumnName="id")
*/
private $primaryClient;
public function __construct()
{
}
public function getPatients(): Patients
{
return $this->patients;
}
public function getPrimaryClient(): Clients
{
return $this->primaryClient;
}
/**
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="datetime")
*/
private $date_created;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_updated;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $date_assigned;
/**
* #ORM\Column(type="smallint")
* #ORM\OneToOne(targetEntity="Employee")
* #ORM\JoinColumn(name="created_by", referencedColumnName="id")
*/
private $created_by;
/**
* #ORM\Column(type="integer")
* #ORM\OneToOne(targetEntity="Attachments")
* #ORM\JoinColumn(name="attachment_id", referencedColumnName="id")
*/
private $attachment_id;
/**
* #ORM\Column(type="integer", nullable=false)
*/
private $patient_id;
/**
* #ORM\Column(type="smallint")
* #Assert\NotBlank(groups = {"insuranceAndCash","cashOnly"}, message="If Payment Type is set to Insurance And Collect or Cash Only then Cash field cannot be blank")
*/
private $payment_type;
/**
* #ORM\Column(type="string", length=50, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","insuranceOnly"}, message="If Payment Type is set to Insurance Only or Insurance And Collect then Insurance Name field cannot be blank")
*/
private $insurance_name;
/**
* #ORM\Column(type="string", length=50, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","insuranceOnly"}, message="If Payment Type is set to Insurance Only or Insurance And Collect then Insurance # field cannot be blank")
*/
private $insurance_no;
/**
* #ORM\Column(type="decimal", precision=15, scale=2, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","cashOnly"}, message="If Payment Type is set to Insurance And Collect or Cash Only then Cash field cannot be blank")
*/
private $cash;
/**
* #ORM\Column(name="primary_client_id", type="integer")
*/
private $primaryClientId;
/**
* One Order has Many Secondary Clients.
* #ORM\ManyToMany(targetEntity="Clients")
* #ORM\JoinTable(name="orders_secondary_clients",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="client_id", referencedColumnName="id")}
* )
*/
private $secondaryClients;
/**
* One Order has Many Employees.
* #ORM\ManyToMany(targetEntity="Employee")
* #ORM\JoinTable(name="orders_employees",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="employee_id", referencedColumnName="id")},
* )
*/
private $employees;
/**
* #ORM\OneToMany(targetEntity="OrderDates", mappedBy="order", cascade={"persist", "remove"}, orphanRemoval=TRUE)
*/
private $dates;
/**
* #ORM\Column(type="text", length=100000, nullable=true)
*/
private $notes;
/**
* #ORM\Column(type="smallint")
*/
private $status = 0;
public function getId(): ?int
{
return $this->id;
}
public function getDateAssigned(): ?\DateTimeInterface
{
return $this->date_assigned;
}
public function setDateAssigned(?\DateTimeInterface $date_assigned): self
{
$this->date_assigned = $date_assigned;
return $this;
}
public function getCreatedBy(): ?int
{
return $this->created_by;
}
public function setCreatedBy(int $created_by): self
{
$this->created_by = $created_by;
return $this;
}
public function getDateCreated(): \DateTimeInterface
{
return $this->date_created;
}
public function setDateCreated(\DateTimeInterface $dateCreated): self
{
$this->date_created = $dateCreated;
return $this;
}
public function getLastUpdated(): ?\DateTimeInterface
{
return $this->last_updated;
}
public function setLastUpdated(?\DateTimeInterface $last_updated): self
{
$this->last_updated = $last_updated;
return $this;
}
public function getPatientId(): ?int
{
return $this->patient_id;
}
public function setPatientId(int $patient_id): self
{
$this->patient_id = $patient_id;
return $this;
}
public function getPaymentType(): ?int
{
return $this->payment_type;
}
public function setPaymentType(int $payment_type): self
{
$this->payment_type = $payment_type;
return $this;
}
public function getInsuranceName(): ?string
{
return $this->insurance_name;
}
public function setInsuranceName(?string $insurance_name): self
{
$this->insurance_name = $insurance_name;
return $this;
}
public function getInsuranceNo(): ?string
{
return $this->insurance_no;
}
public function setInsuranceNo(?string $insurance_no): self
{
$this->insurance_no = $insurance_no;
return $this;
}
public function getCash() : float
{
return $this->cash;
}
public function setCash(float $cash): self
{
$this->cash = $cash;
return $this;
}
public function getAttachmentId(): ?int
{
return $this->attachment_id;
}
public function setAttachmentId(int $attachment_id): self
{
$this->attachment_id = $attachment_id;
return $this;
}
public function getPrimaryClientId(): int
{
return $this->primaryClientId;
}
public function setPrimaryClientId(int $client): self
{
$this->primaryClientId = $client;
return $this;
}
public function getSecondaryClients() : ?PersistentCollection
{
return $this->secondaryClients;
}
public function setSecondaryClients(?array $clients): self
{
$this->secondaryClients = $clients;
return $this;
}
public function getEmployees() : PersistentCollection
{
return $this->employees;
}
public function setEmployees(array $employees): self
{
$this->employees = $employees;
return $this;
}
public function getDates() : PersistentCollection
{
return $this->dates;
}
public function addDate(\DateTime $date): self
{
$orderDate = new OrderDates();
$orderDate->setDate($date);
$orderDate->setOrder($this);
$this->dates[] = $orderDate;
return $this;
}
public function setDates(array $dates): self
{
foreach($dates as $date)
{
$this->addDate(new \DateTime($date));
}
return $this;
}
public function getNotes() : ?string
{
return $this->notes;
}
public function setNotes(?string $notes): self
{
$this->notes = $notes;
return $this;
}
public function getStatus() : int
{
return $this->status;
}
public function setStatus(int $status): self
{
$this->notes = $status;
return $this;
}
public function getGroupSequence()
{
$group = null;
switch($this->payment_type) {
case self::TYPE_InsuranceOnly:
$group = 'insuranceOnly';
break;
case self::TYPE_InsuranceAndCash:
$group = 'insuranceAndCash';
break;
case self::TYPE_CashOnly:
$group = 'cashOnly';
break;
}
return [
[
'Orders',
$group
]
];
}
}
EDIT:
I decided to just run the SQL statement output by the persist against the DB and it seems not only was the patient missing but also the primary_client_id field. I now assume it has something to do with the associations I have in there for patients and primaryclient since those are the two fields that are missing. I'm not sure what would be wrong there though.
For the sake of posterity, after the discussion in the post comments this is the end result of my entity. It now saves the id's in the table, there was no need for a separate field JUST to save the int. The only big difference is I need to lookup the patient and primary Client to pass in, instead of just passing the id value (integer).
Code:
$patient = $this->getDoctrine()
->getRepository(Patients::class)
->find($order->getPatientId());
$primaryClient = $this->getDoctrine()
->getRepository(Clients::class)
->findOneById($order->getPrimaryClient());
$db_order = new Orders();
$db_order->setDateCreated(new \DateTime());
$db_order->setLastUpdated(null);
$db_order->setDateAssigned(null);
$db_order->setCreatedBy($user->getId());
$db_order->setAttachmentId($order->getFaxId());
$db_order->setPatient($patient);
$db_order->setPaymentType($order->getPaymentType());
$db_order->setInsuranceName($order->getInsuranceName());
$db_order->setInsuranceNo($order->getInsuranceNo());
$db_order->setCash($order->getCash());
$db_order->setPrimaryClient($primaryClient);
$db_order->setSecondaryClients($secondaryClients);
$db_order->setEmployees($employees);
$db_order->setDates($dates);
$db_order->setNotes($note);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($db_order);
$entityManager->flush();
Entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\GroupSequenceProviderInterface;
/**
* #ORM\Entity(repositoryClass="App\Repository\OrdersRepository")
* #Assert\GroupSequenceProvider()
*/
class Orders implements GroupSequenceProviderInterface
{
const TYPE_InsuranceOnly = 1;
const TYPE_InsuranceAndCash = 2;
const TYPE_CashOnly = 3;
/**
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="datetime")
*/
private $date_created;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_updated;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $date_assigned;
/**
* #ORM\Column(type="smallint")
* #ORM\OneToOne(targetEntity="Employee")
* #ORM\JoinColumn(name="created_by", referencedColumnName="id")
*/
private $created_by;
/**
* #ORM\Column(type="integer")
* #ORM\OneToOne(targetEntity="Attachments")
* #ORM\JoinColumn(name="attachment_id", referencedColumnName="id")
*/
private $attachment_id;
/**
* #ORM\Column(type="smallint")
* #Assert\NotBlank(groups = {"insuranceAndCash","cashOnly"}, message="If Payment Type is set to Insurance And Collect or Cash Only then Cash field cannot be blank")
*/
private $payment_type;
/**
* #ORM\Column(type="string", length=50, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","insuranceOnly"}, message="If Payment Type is set to Insurance Only or Insurance And Collect then Insurance Name field cannot be blank")
*/
private $insurance_name;
/**
* #ORM\Column(type="string", length=50, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","insuranceOnly"}, message="If Payment Type is set to Insurance Only or Insurance And Collect then Insurance # field cannot be blank")
*/
private $insurance_no;
/**
* #ORM\Column(type="decimal", precision=15, scale=2, nullable=true)
* #Assert\NotBlank(groups = {"insuranceAndCash","cashOnly"}, message="If Payment Type is set to Insurance And Collect or Cash Only then Cash field cannot be blank")
*/
private $cash;
/**
* One Order has Many Secondary Clients.
* #ORM\ManyToMany(targetEntity="Clients")
* #ORM\JoinTable(name="orders_secondary_clients",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="client_id", referencedColumnName="id")}
* )
*/
private $secondaryClients;
/**
* One Order has Many Employees.
* #ORM\ManyToMany(targetEntity="Employee")
* #ORM\JoinTable(name="orders_employees",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="employee_id", referencedColumnName="id")},
* )
*/
private $employees;
/**
* #ORM\OneToMany(targetEntity="OrderDates", mappedBy="order", cascade={"persist", "remove"}, orphanRemoval=TRUE)
*/
private $dates;
/**
* #ORM\Column(type="text", length=100000, nullable=true)
*/
private $notes;
/**
* #ORM\Column(type="smallint")
*/
private $status = 0;
/**
* #ORM\ManyToOne(targetEntity="Patients")
* #ORM\JoinColumn(name="patient_id", referencedColumnName="id")
*/
private $patient;
/**
* #ORM\ManyToOne(targetEntity="Clients")
* #ORM\JoinColumn(name="primary_client_id", referencedColumnName="id")
*/
private $primaryClient;
public function getId(): ?int
{
return $this->id;
}
public function getDateAssigned(): ?\DateTimeInterface
{
return $this->date_assigned;
}
public function setDateAssigned(?\DateTimeInterface $date_assigned): self
{
$this->date_assigned = $date_assigned;
return $this;
}
public function getCreatedBy(): ?int
{
return $this->created_by;
}
public function setCreatedBy(int $created_by): self
{
$this->created_by = $created_by;
return $this;
}
public function getDateCreated(): \DateTimeInterface
{
return $this->date_created;
}
public function setDateCreated(\DateTimeInterface $dateCreated): self
{
$this->date_created = $dateCreated;
return $this;
}
public function getLastUpdated(): ?\DateTimeInterface
{
return $this->last_updated;
}
public function setLastUpdated(?\DateTimeInterface $last_updated): self
{
$this->last_updated = $last_updated;
return $this;
}
public function getPaymentType(): ?int
{
return $this->payment_type;
}
public function setPaymentType(int $payment_type): self
{
$this->payment_type = $payment_type;
return $this;
}
public function getInsuranceName(): ?string
{
return $this->insurance_name;
}
public function setInsuranceName(?string $insurance_name): self
{
$this->insurance_name = $insurance_name;
return $this;
}
public function getInsuranceNo(): ?string
{
return $this->insurance_no;
}
public function setInsuranceNo(?string $insurance_no): self
{
$this->insurance_no = $insurance_no;
return $this;
}
public function getCash() : float
{
return $this->cash;
}
public function setCash(float $cash): self
{
$this->cash = $cash;
return $this;
}
public function getAttachmentId(): ?int
{
return $this->attachment_id;
}
public function setAttachmentId(int $attachment_id): self
{
$this->attachment_id = $attachment_id;
return $this;
}
public function getSecondaryClients() : ?PersistentCollection
{
return $this->secondaryClients;
}
public function setSecondaryClients(?array $clients): self
{
$this->secondaryClients = $clients;
return $this;
}
public function getEmployees() : PersistentCollection
{
return $this->employees;
}
public function setEmployees(array $employees): self
{
$this->employees = $employees;
return $this;
}
public function getDates() : PersistentCollection
{
return $this->dates;
}
public function addDate(\DateTime $date): self
{
$orderDate = new OrderDates();
$orderDate->setDate($date);
$orderDate->setOrder($this);
$this->dates[] = $orderDate;
return $this;
}
public function setDates(array $dates): self
{
foreach($dates as $date)
{
$this->addDate(new \DateTime($date));
}
return $this;
}
public function getNotes() : ?string
{
return $this->notes;
}
public function setNotes(?string $notes): self
{
$this->notes = $notes;
return $this;
}
public function getStatus() : int
{
return $this->status;
}
public function setStatus(int $status): self
{
$this->notes = $status;
return $this;
}
public function getGroupSequence()
{
$group = null;
switch($this->payment_type) {
case self::TYPE_InsuranceOnly:
$group = 'insuranceOnly';
break;
case self::TYPE_InsuranceAndCash:
$group = 'insuranceAndCash';
break;
case self::TYPE_CashOnly:
$group = 'cashOnly';
break;
}
return [
[
'Orders',
$group
]
];
}
public function getPatient(): Patients
{
return $this->patient;
}
public function setPatient(Patients $patient) : self
{
$this->patient = $patient;
return $this;
}
public function getPrimaryClient(): Clients
{
return $this->primaryClient;
}
pu]

Doctrine query error unknow column

I'm using Doctrine in my Symfony3 project. I'm using the entity manager to get my data from the database but I have an unexpected error which seems to be generated by doctrine.
An exception has been thrown during the rendering of a template ("An exception occurred while executing 'SELECT t0.id AS id_1, t0.date AS date_2, t0.comment AS comment_3, t0.viewed AS viewed_4, t0.error_count AS error_count_5, t0.of_id AS of_id_6, t0.checkpoint_id AS checkpoint_id_7, t8.id AS id_9, t8.name AS name_10, t8.description AS description_11, t8.deleted_at AS deleted_at_12, t8.factory_id AS factory_id_13, t0.operateur_id AS operateur_id_15, t0.factory_id AS factory_id_16 FROM app_check_set t0 LEFT JOIN app_checkpoint t8 ON t0.checkpoint_id = t14.id AND ((t14.deleted_at IS NULL)) WHERE t0.factory_id = ? ORDER BY t0.date DESC LIMIT 5' with params [3]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 't14.id' in 'on clause'").
As I'm not creating the query myself, i would like to know where is this error coming from ? Is it related with my entity configuration ?
The problem is when I want to get my entities Checkset :
public function notificationsAction(Request $request){
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
return $this->render('AppBundle:Home:notifications.html.twig', array(
'notifications' => $em->getRepository('AppBundle:CheckSet')->findBy(array('factory' => $user->getFactory()->getId()), array('date' => 'desc'), 5),
'count' => count($em->getRepository('AppBundle:CheckSet')->findBy(array('factory' => $user->getFactory()->getId(), 'viewed' => false)))
));
}
My entities are like this :
CheckSet:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use UserBundle\Entity\User;
use Doctrine\Common\Collections\ArrayCollection;
/**
* CheckSet
*
* #ORM\Table(name="app_check_set")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CheckSetRepository")
*/
class CheckSet
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #var string
* #ORM\Column(name="comment", type="text", nullable=true)
*/
private $comment;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElementResult", mappedBy="checkSet", cascade={"persist"})
*/
private $checkElementResult;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElementResultObservation", mappedBy="checkSet", cascade={"persist"})
*/
private $observations;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Of", inversedBy="checkSet")
* #ORM\JoinColumn(name="of_id", referencedColumnName="id")
*/
private $of;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\CheckPoint", inversedBy="checkSet", fetch="EAGER")
* #ORM\JoinColumn(name="checkpoint_id", referencedColumnName="id")
*/
private $checkPoint;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="checkSet")
* #ORM\JoinColumn(name="operateur_id", referencedColumnName="id")
*/
private $operateur;
/**
* #ORM\Column(type="boolean", nullable=false, options={"default" : false})
*/
protected $viewed = FALSE;
/**
* #ORM\Column(type="integer", nullable=false)
*/
protected $errorCount;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Factory", inversedBy="checkSet")
* #ORM\JoinColumn(name="factory_id", referencedColumnName="id")
*/
private $factory;
public function __construct($gamme = null, $of = null, $user = null){
$this->checkElementResult = new ArrayCollection();
$this->observations = new ArrayCollection();
$this->date = new \DateTime();
$this->errorCount = 0;
if ($gamme != null){
$this->checkPoint = $gamme;
}
if ($of != null){
$this->of = $of;
}
if ($user != null){
$this->operateur = $user;
$this->factory = $user->getFactory();
}
}
public function getId(){
return $this->id;
}
public function setDate($date){
$this->date = $date;
return $this;
}
public function getDate(){
return $this->date;
}
public function setErrorCount($errorCount){
$this->errorCount = $errorCount;
return $this;
}
public function getErrorCount(){
return $this->errorCount;
}
public function setComment($comment){
$this->comment = $comment;
return $this;
}
public function getComment(){
return $this->comment;
}
public function setOperateur(User $operateur){
$this->operateur = $operateur;
return $this;
}
public function getOperateur(){
return $this->operateur;
}
public function setOf(Of $of){
$this->of = $of;
return $this;
}
public function getOf(){
return $this->of;
}
public function setFactory(Factory $factory){
$this->factory = $factory;
return $this;
}
public function getFactory(){
return $this->factory;
}
public function setCheckPoint(Checkpoint $checkPoint){
$this->checkPoint = $checkPoint;
return $this;
}
public function getCheckPoint(){
return $this->checkPoint;
}
/*------------------------------------------------------------------------CheckElementResult*/
public function addCheckElementResult(CheckElementResult $cke){
$this->checkElementResult[] = $cke;
$cke->setCheckSet($this);
return $this;
}
public function removeCheckElementResult(CheckElementResult $cke){
$this->checkElementResult->removeElement($cke);
}
public function getcheckElementResult(){
return $this->checkElementResult;
}
/*------------------------------------------------------------------------observations*/
public function addObservations(CheckElementResultObservation $cke){
$this->observations[] = $cke;
$cke->setCheckSet($this);
return $this;
}
public function removeObservations(CheckElementResultObservation $cke){
$this->observations->removeElement($cke);
}
public function getObservations(){
return $this->observations;
}
/*-------------------------------------------------------VIEWED*/
public function setViewed($viewed){
$this->viewed = $viewed;
return $this;
}
public function getViewed(){
return $this->viewed;
}
public function isViewed(){
return $this->viewed;
}
public function countErrors(){
$err = 0;
foreach ($this->checkElementResult as $key => $ckeR) {
foreach ($ckeR->getCheckElement()->getAlert() as $key => $alert) {
if( $alert->getOperator() == "==" && $ckeR->getValue() == $alert->getValue()){
$err++;
}elseif ( $alert->getOperator() == "!=" && $ckeR->getValue() != $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == "<" && $ckeR->getValue() < $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == ">" && $ckeR->getValue() > $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == "<=" && $ckeR->getValue() <= $alert->getValue()) {
$err++;
}elseif ( $alert->getOperator() == ">=" && $ckeR->getValue() >= $alert->getValue()) {
$err++;
}
}
}
return $err;
}
public function __toString(){
return $this->of->getName().' '.$this->checkPoint->getName();
}
}
CheckPoint:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Checkpoint
*
* #ORM\Table(name="app_checkpoint")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CheckpointRepository")
* #Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
*/
class Checkpoint
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckElement", mappedBy="checkpoint",cascade={"persist"}, orphanRemoval=true)
* #ORM\OrderBy({"position" = "ASC"})
*/
private $checkElements;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Operation", mappedBy="checkpoint",cascade={"persist"})
*/
private $operation;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Factory", inversedBy="checkpoints")
* #ORM\JoinColumn(name="factory_id", referencedColumnName="id")
*/
private $factory;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckSet", mappedBy="checkPoint")
*/
private $checkSet;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CheckListOf", mappedBy="checkPoint")
*/
private $checkListOf;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $deletedAt;
public function __construct(){
$this->checkElements = new ArrayCollection();
}
public function getId(){
return $this->id;
}
public function setName($name){
$this->name = $name;
return $this;
}
public function getName(){
return $this->name;
}
public function setDescription($description){
$this->description = $description;
return $this;
}
public function getDescription(){
return $this->description;
}
public function getFactory(){
return $this->factory;
}
public function setFactory($factory){
$this->factory = $factory;
}
/*------------------------------------------------------------------------Checkelements*/
public function addCheckElement(CheckElement $cke){
$this->checkElements[] = $cke;
$cke->setCheckpoint($this);
return $this;
}
public function removeCheckElement(CheckElement $cke){
$this->checkElements->removeElement($cke);
}
public function getCheckElements(){
return $this->checkElements;
}
public function __toString(){
return $this->name;
}
}
The problem could be because of the soft delete but I'm not sure ... The controller I'm calling (notificationsAction) is embed in my header.
In this page (the notifications area) I want to display objects which may have been deleted. The problem happend when the checkpoint I want to display (the one related to the Checkset objects) has been deleted
<!-- NOTIFICATIONS -->
{{ render(controller('AppBundle:Home:notifications', {'request': app.request})) }}
Your issue is actually the same as here.
Your class name is Checkpoint and I guess the file is named checkpoint.php (note that if you are developing on windows, the filename is case-insensitive). All are lowercase.
In your CheckSet class you have
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\CheckPoint", inversedBy="checkSet", fetch="EAGER")
* #ORM\JoinColumn(name="checkpoint_id", referencedColumnName="id")
*/
private $checkPoint;
The targetEntity is to "AppBundle\Entity\CheckPoint" with capital P.
The issue is that because of this, doctrine create a new alias for a new table (the php comparison is case sensitive github link).
To solve this, change your class name and file to CheckPoint with capital P:
class CheckPoint
{

Entity 'models\ForgottenLogin' has a composite identifier but uses an ID generator other than manually assigning (Identity, Sequence)

When I try to do this
$forgottenLoginRepo = $this->doctrine->em->getRepository('models\ForgottenLogin');
$forgottenLogin = $forgottenLoginRepo->findOneBy(
array(
'passwordKey' => $key
)
);
I get this error
Entity 'models\ForgottenLogin' has a composite identifier but uses an
ID generator other than manually assigning (Identity, Sequence). This
is not supported.
My model is
<?php
/**
* Created by PhpStorm.
* User: Manisha.DeSilva
* Date: 06/07/2017
* Time: 13:03
*/
namespace models;
/**
* #Entity
* #Table(name="park_forgotten_login")
*
*/
class ForgottenLogin
{
/**
* #Id
* #Column(name="id", type="integer", nullable=false)
* #GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
}
/**
* #Id
* #ManyToOne(targetEntity="Customer")
* #JoinColumn(name="customer_id", referencedColumnName="id")
*/
private $customer;
public function getCustomer()
{
return $this->customer;
}
public function setCustomer($value)
{
$this->customer = $value;
}
/**
* #Column(name="password_Key", type="string", nullable=false)
*/
private $passwordKey;
public function getPasswordKey()
{
return $this->passwordKey;
}
public function setPasswordKey($value)
{
$this->passwordKey = $value;
}
/**
* #Column(name="expiry", type="datetime", nullable=false)
*/
private $expiry;
public function getExpiry()
{
return $this->expiry;
}
public function setExpiry($value)
{
$this->expiry = $value;
}
private $forgottenFlag;
public function getForgottenFlag()
{
return $this->forgottenFlag;
}
public function setForgottenFlag($value)
{
$this->forgottenFlag = $value;
}
}

Doctrine\ORM\Mapping\MappingException Duplicate definition of column 'username' on entity

I am using FOSUserBundle but I wanted to rename the roles field column name to user_roles for legacy database,
By referring to
https://github.com/FriendsOfSymfony/FOSUserBundle/issues/338
and
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/doctrine.md#replacing-the-mapping-of-the-bundle
I am trying to overwrite the existing FOS\UserBundle\Model\User with my AcmeDemoBundle:User entity by mapping all fields again.
This is my Class,
PLEASE NOTE I AM EXTENDING ENTITY DIRECTLY FROM "FOS\UserBundle\Model\User"
namespace Acme\SecurityBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Acme\CommonBundle\Util\Url as Url;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="Acme\SecurityBundle\Entity\UserRepository")
*/
Class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="username", type="string", length=255)
*/
protected $username;
/**
* #var string
* #ORM\Column(name="username_canonical", type="string", length=255, unique=true)
*/
protected $usernameCanonical;
/**
* #var string
* #ORM\Column(name="email", type="string", length=255)
*/
protected $email;
/**
* #var string
* #ORM\Column(name="email_canonical", type="string", length=255, unique=true)
*/
protected $emailCanonical;
/**
* #var boolean
* #ORM\Column(name="enabled", type="boolean")
*/
protected $enabled;
/**
* The salt to use for hashing
*
* #var string
* #ORM\Column(name="salt", type="string")
*/
protected $salt;
/**
* Encrypted password. Must be persisted.
*
* #var string
* #ORM\Column(name="password", type="string")
*/
protected $password;
/**
* Plain password. Used for model validation. Must not be persisted.
*
* #var string
*/
protected $plainPassword;
/**
* #var \DateTime
* #ORM\Column(name="last_login", type="datetime", nullable=true)
*/
protected $lastLogin;
/**
* Random string sent to the user email address in order to verify it
*
* #var string
* #ORM\Column(name="confirmation_token", type="string", nullable=true)
*/
protected $confirmationToken;
/**
* #var \DateTime
* #ORM\Column(name="password_requested_at", type="datetime", nullable=true)
*/
protected $passwordRequestedAt;
/**
* #var Collection
*/
protected $groups;
/**
* #var boolean
* #ORM\Column(name="locked", type="boolean")
*/
protected $locked;
/**
* #var boolean
* #ORM\Column(name="expired", type="boolean")
*/
protected $expired;
/**
* #var \DateTime
* #ORM\Column(name="expires_at", type="datetime", nullable=true)
*/
protected $expiresAt;
/**
* #var array
* #ORM\Column(name="fos_roles", type="array", nullable=true)
*/
protected $roles;
/**
* #var boolean
* #ORM\Column(name="credentials_expired", type="boolean")
*/
protected $credentialsExpired;
/**
* #var \DateTime
* #ORM\Column(name="credentials_expire_at", type="datetime", nullable=true)
*/
protected $credentialsExpireAt;
public function __construct()
{
parent::__construct();
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
$this->enabled = false;
$this->locked = false;
$this->expired = false;
$this->roles = array();
$this->credentialsExpired = false;
//$this->setEmailHash();
}
public function addRole($role)
{
$role = strtoupper($role);
if ($role === static::ROLE_DEFAULT) {
return $this;
}
if (!in_array($role, $this->roles, true)) {
$this->roles[] = $role;
}
return $this;
}
/**
* Serializes the user.
*
* The serialized data have to contain the fields used by the equals method and the username.
*
* #return string
*/
public function serialize()
{
return serialize(array(
$this->password,
$this->salt,
$this->usernameCanonical,
$this->username,
$this->expired,
$this->locked,
$this->credentialsExpired,
$this->enabled,
$this->id,
));
}
/**
* Unserializes the user.
*
* #param string $serialized
*/
public function unserialize($serialized)
{
$data = unserialize($serialized);
// add a few extra elements in the array to ensure that we have enough keys when unserializing
// older data which does not include all properties.
$data = array_merge($data, array_fill(0, 2, null));
list(
$this->password,
$this->salt,
$this->usernameCanonical,
$this->username,
$this->expired,
$this->locked,
$this->credentialsExpired,
$this->enabled,
$this->id
) = $data;
}
/**
* Removes sensitive data from the user.
*/
public function eraseCredentials()
{
$this->plainPassword = null;
}
/**
* Returns the user unique id.
*
* #return mixed
*/
public function getId()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function getUsernameCanonical()
{
return $this->usernameCanonical;
}
public function getSalt()
{
return $this->salt;
}
public function getEmail()
{
return $this->email;
}
public function getEmailCanonical()
{
return $this->emailCanonical;
}
/**
* Gets the encrypted password.
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* Gets the last login time.
*
* #return \DateTime
*/
public function getLastLogin()
{
return $this->lastLogin;
}
public function getConfirmationToken()
{
return $this->confirmationToken;
}
/**
* Returns the user roles
*
* #return array The roles
*/
public function getRoles()
{
$roles = $this->roles;
foreach ($this->getGroups() as $group) {
$roles = array_merge($roles, $group->getRoles());
}
// we need to make sure to have at least one role
$roles[] = static::ROLE_DEFAULT;
return array_unique($roles);
}
/**
* Never use this to check if this user has access to anything!
*
* Use the SecurityContext, or an implementation of AccessDecisionManager
* instead, e.g.
*
* $securityContext->isGranted('ROLE_USER');
*
* #param string $role
*
* #return boolean
*/
public function hasRole($role)
{
return in_array(strtoupper($role), $this->getRoles(), true);
}
public function isAccountNonExpired()
{
if (true === $this->expired) {
return false;
}
if (null !== $this->expiresAt && $this->expiresAt->getTimestamp() < time()) {
return false;
}
return true;
}
public function isAccountNonLocked()
{
return !$this->locked;
}
public function isCredentialsNonExpired()
{
if (true === $this->credentialsExpired) {
return false;
}
if (null !== $this->credentialsExpireAt && $this->credentialsExpireAt->getTimestamp() < time()) {
return false;
}
return true;
}
public function isCredentialsExpired()
{
return !$this->isCredentialsNonExpired();
}
public function isEnabled()
{
return $this->enabled;
}
public function isExpired()
{
return !$this->isAccountNonExpired();
}
public function isLocked()
{
return !$this->isAccountNonLocked();
}
public function isSuperAdmin()
{
return $this->hasRole(static::ROLE_SUPER_ADMIN);
}
public function isUser(\FOS\UserBundle\Model\UserInterface $user = null)
{
return null !== $user && $this->getId() === $user->getId();
}
public function removeRole($role)
{
if (false !== $key = array_search(strtoupper($role), $this->roles, true)) {
unset($this->roles[$key]);
$this->roles = array_values($this->roles);
}
return $this;
}
public function setUsername($username)
{
$this->username = $username;
return $this;
}
public function setUsernameCanonical($usernameCanonical)
{
$this->usernameCanonical = $usernameCanonical;
return $this;
}
/**
* #param \DateTime $date
*
* #return User
*/
public function setCredentialsExpireAt(\DateTime $date = null)
{
$this->credentialsExpireAt = $date;
return $this;
}
/**
* #param boolean $boolean
*
* #return User
*/
public function setCredentialsExpired($boolean)
{
$this->credentialsExpired = $boolean;
return $this;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
public function setEmailCanonical($emailCanonical)
{
$this->emailCanonical = $emailCanonical;
return $this;
}
public function setEnabled($boolean)
{
$this->enabled = (Boolean) $boolean;
return $this;
}
/**
* Sets this user to expired.
*
* #param Boolean $boolean
*
* #return User
*/
public function setExpired($boolean)
{
$this->expired = (Boolean) $boolean;
return $this;
}
/**
* #param \DateTime $date
*
* #return User
*/
public function setExpiresAt(\DateTime $date = null)
{
$this->expiresAt = $date;
return $this;
}
public function setPassword($password)
{
$this->password = $password;
return $this;
}
public function setSuperAdmin($boolean)
{
if (true === $boolean) {
$this->addRole(static::ROLE_SUPER_ADMIN);
} else {
$this->removeRole(static::ROLE_SUPER_ADMIN);
}
return $this;
}
public function setPlainPassword($password)
{
$this->plainPassword = $password;
return $this;
}
public function setLastLogin(\DateTime $time = null)
{
$this->lastLogin = $time;
return $this;
}
public function setLocked($boolean)
{
$this->locked = $boolean;
return $this;
}
public function setConfirmationToken($confirmationToken)
{
$this->confirmationToken = $confirmationToken;
return $this;
}
public function setPasswordRequestedAt(\DateTime $date = null)
{
$this->passwordRequestedAt = $date;
return $this;
}
/**
* Gets the timestamp that the user requested a password reset.
*
* #return null|\DateTime
*/
public function getPasswordRequestedAt()
{
return $this->passwordRequestedAt;
}
public function isPasswordRequestNonExpired($ttl)
{
return $this->getPasswordRequestedAt() instanceof \DateTime &&
$this->getPasswordRequestedAt()->getTimestamp() + $ttl > time();
}
public function setRoles(array $roles)
{
$this->roles = array();
foreach ($roles as $role) {
$this->addRole($role);
}
return $this;
}
/**
* Gets the groups granted to the user.
*
* #return Collection
*/
public function getGroups()
{
return $this->groups ? : $this->groups = new ArrayCollection();
}
public function getGroupNames()
{
$names = array();
foreach ($this->getGroups() as $group) {
$names[] = $group->getName();
}
return $names;
}
public function hasGroup($name)
{
return in_array($name, $this->getGroupNames());
}
public function addGroup(\FOS\UserBundle\Model\GroupInterface $group)
{
if (!$this->getGroups()->contains($group)) {
$this->getGroups()->add($group);
}
return $this;
}
public function removeGroup(\FOS\UserBundle\Model\GroupInterface $group)
{
if ($this->getGroups()->contains($group)) {
$this->getGroups()->removeElement($group);
}
return $this;
}
public function __toString()
{
return (string) $this->getUsername();
}
}
If I remove extends BaseUser (FOS\UserBundle\Model\User), it gives error "The user provider must return a UserInterface object."
Then I tried adding "implements UserInterface, GroupableInterface" but it still gives "There is no user provider for user "Acme\SecurityBundle\Entity\User".
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Model/User.php
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/config/doctrine/model/User.orm.xml
The property username is already defined in FOS\UserBundle\Model\User. Its metadata is in their resources config. So you are defining that column twice essentially.
We dont need to overwrite all fields to rename the field in database, I could achieve this by using AttributeOverride
/**
* #ORM\Entity
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="Acme\SecurityBundle\Entity\UserRepository")
* #ORM\AttributeOverrides({
* #ORM\AttributeOverride(name="roles",
* column=#ORM\Column(
* name = "user_roles",
* type = "array"
* )
* )
* })
*/
Class User extends BaseUser
{
...
}
#Fosculus: what about the property id? It's also defined in FOS\UserBundle\Model\User. Why doesn't it give any problem?

Categories