I have a number of entities (automatically generated with Symfony2 Console) that are structured as follows in the database:
The entity generated is as follows:
class Offers
{
/**
* #var string
* #Assert\Length(
* min = 5,
* max = 64,
* minMessage = "El nombre de la oferta debe de tener al menos {{ limit }} caracteres.",
* maxMessage = "El nombre de la oferta no puede superar los {{ limit }} caracteres."
* )
*/
private $name;
/**
* #var string
*/
private $description;
/**
* #var string
* #Assert\Url(message = "La url '{{ value }}' no es válida")
*/
private $url;
/**
* #var string
*/
private $img;
/**
* #var \DateTime
*/
private $dateFrom;
/**
* #var \DateTime
*/
private $dateTo;
/**
* #var \DateTime
*/
private $registered;
/**
* #var boolean
*/
private $active;
/**
* #var integer
*/
private $availableFor;
/**
* #var integer
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $idState;
/**
* Constructor
*/
public function __construct()
{
$this->idState = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set name
*
* #param string $name
* #return Offers
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Offers
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set url
*
* #param string $url
* #return Offers
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set img
*
* #param string $img
*/
public function setImg($img = null)
{
if ( $img != null)
$this->img = $img;
}
/**
* Get img
*
* #return string
*/
public function getImg()
{
return $this->img;
}
/**
* Set dateFrom
*
* #param \DateTime $dateFrom
* #return Offers
*/
public function setDateFrom($dateFrom)
{
$this->dateFrom = $dateFrom;
return $this;
}
/**
* Get dateFrom
*
* #return \DateTime
*/
public function getDateFrom()
{
return $this->dateFrom;
}
/**
* Set dateTo
*
* #param \DateTime $dateTo
* #return Offers
*/
public function setDateTo($dateTo)
{
$this->dateTo = $dateTo;
return $this;
}
/**
* Get dateTo
*
* #return \DateTime
*/
public function getDateTo()
{
return $this->dateTo;
}
/**
* Set registered
*
* #param \DateTime $registered
* #return Offers
*/
public function setRegistered($registered)
{
$this->registered = $registered;
return $this;
}
/**
* Get registered
*
* #return \DateTime
*/
public function getRegistered()
{
return $this->registered;
}
/**
* Set active
*
* #param boolean $active
* #return Offers
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
* Get active
*
* #return boolean
*/
public function getActive()
{
return $this->active;
}
/**
* Set availableFor
*
* #param integer $availableFor
* #return Offers
*/
public function setAvailableFor($availableFor)
{
$this->availableFor = $availableFor;
return $this;
}
/**
* Get availableFor
*
* #return integer
*/
public function getAvailableFor()
{
return $this->availableFor;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add idState
*
* #param \Consolidador\PanelBundle\Entity\States $idState
* #return Offers
*/
public function addIdState(\Consolidador\PanelBundle\Entity\States $idState)
{
$this->idState[] = $idState;
return $this;
}
/**
* Remove idState
*
* #param \Consolidador\PanelBundle\Entity\States $idState
*/
public function removeIdState(\Consolidador\PanelBundle\Entity\States $idState)
{
$this->idState->removeElement($idState);
}
/**
* Get idState
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdState()
{
return $this->idState;
}
/**
* Set idState
* #param \Consolidador\PanelBundle\Entity\States $idState
*/
public function setIdState($idState)
{
$this->idState[] = $idState;
}
/**
* Cadena de texto a devolver.
* #return string
*/
public function __toString()
{
return $this->name;
}
It turns out that I select tenders belonging to a particular state, and what I do is this:
$dql = $em->createQuery("SELECT o FROM PanelBundle:Offers o WHERE o.idState = :state");
$dql->setParameter('state', $this->getUser()->getIdAgency()->getIdZone()->getIdState());
$offersState = $dql->getResult();
But I returned the following error:
[Semantical Error] line 0, col 43 near 'idState = :s': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.
Does anyone has thought of something? Do you know how to consult in such institutions?
Greetings and thank you
SOLVED:
Here are the DQL queries used for offerings of a particular state and for all offers that do not belong to any (independent). There may be a more simple way, if anyone knows, you publish it.
SELECT o FROM PanelBundle:Offers o JOIN o.idState os WHERE os.id = :state
SELECT o FROM PanelBundle:Offers o WHERE o.id NOT IN (SELECT x.id FROM PanelBundle:Offers x JOIN x.idState os)
You should JOIN to states table.
$qb
->from('PanelBundle:Offers', 'o')
->select('o')
->join('PanelBundle:States', 's')
->andWhere('o.state = :state');
// ....
Related
First, forgive me for my bad English.
I have a problem with an sql query that I am doing using doctrine in symfony
I have two related tables, one of users and one of actions performed by the user, these tables are related from one to many, a user can do many actions.
I am trying to make a query in which I from all users who have not done an action (the status column is the one that indicates the types of actions, when the process ends it will have an 8) therefore I want to remove those that do not have an 8. In principle, although I have tried many options, what I think would be more correct would be
$query = $em->createQueryBuilder()
->from("BackendBundle:Inscritos", "e")
->select("e")
->innerJoin("BackendBundle:InscritosAcciones", "u", "WITH", "e.id=u.inscritosId")
->groupBy("u.inscritosId")
->where("u.status != 8")
->getQuery();
The fact is that as the user has some other action besides that of status 8 (must have them since it is a process and the actions allow to see what has been happening) I continue to remove that user.
my entities
namespace BackendBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Inscritos
* #UniqueEntity(fields={"correoUsuario"}, message="¡Este correo ya esta registrado!")
* #UniqueEntity(fields={"documento"}, message="¡Este numero de documento ya esta registrado!")
*/
class Inscritos {
/**
* #var integer
*/
private $id;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tu nombre")
*/
private $nombreUsuario;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tus apellidos")
*/
private $apellidoUsuario;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Range(
* min = 9,
* max = 9,
* minMessage = "Este campo tiene que tener {{ limit }} numeros ",
* maxMessage = "Este campo tiene que tener {{ limit }} numeros "
* )
*/
private $telefono;
/**
* #var string
* #Assert\Email(checkMX=true)
*/
private $correoUsuario;
/**
* #var string
*/
private $validadocorreo = 'NO';
/**
* #var string
*/
private $tipodocumento;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tu numero de documento")
*/
private $documento;
/**
* #var \DateTime
* #Assert\NotBlank(message = "Por favor, escribe tu fecha de nacimiento")
*/
private $fechanacimiento;
/**
* #var string
*/
private $pais;
/**
* #var string
*/
private $provinciaotros;
/**
* #var string
*/
private $municipiootros;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tu codigo postal")
*/
private $codigopostal;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tu direccion de contacto")
*/
private $direccion;
/**
* #var string
*/
private $lugarparticipacion;
/**
* #var \DateTime
*/
private $fechainscritpcion;
/**
* #var string
*/
private $ipinscripcion;
/**
* #var string
*/
private $cadenaseg;
/**
* #var string
*/
private $bloqueo = 'no';
/**
* #var string
*/
private $razonBloqueo;
/**
* #var string
*/
private $perfil;
/**
* #var \DateTime
*/
private $fechaControl;
/**
* #var integer
*/
private $idMunicipio;
/**
* #var integer
*/
private $idProvincia;
/**
* #var string
*/
private $idCcaa;
public function __toString() {
return (string) $this->getId();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set nombreUsuario
*
* #param string $nombreUsuario
*
* #return Inscritos
*/
public function setNombreUsuario($nombreUsuario) {
$this->nombreUsuario = $nombreUsuario;
return $this;
}
/**
* Get nombreUsuario
*
* #return string
*/
public function getNombreUsuario() {
return $this->nombreUsuario;
}
/**
* Set apellidoUsuario
*
* #param string $apellidoUsuario
*
* #return Inscritos
*/
public function setApellidoUsuario($apellidoUsuario) {
$this->apellidoUsuario = $apellidoUsuario;
return $this;
}
/**
* Get apellidoUsuario
*
* #return string
*/
public function getApellidoUsuario() {
return $this->apellidoUsuario;
}
/**
* Set telefono
*
* #param string $telefono
*
* #return Inscritos
*/
public function setTelefono($telefono) {
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* #return string
*/
public function getTelefono() {
return $this->telefono;
}
/**
* Set correoUsuario
*
* #param string $correoUsuario
*
* #return Inscritos
*/
public function setCorreoUsuario($correoUsuario) {
$this->correoUsuario = $correoUsuario;
return $this;
}
/**
* Get correoUsuario
*
* #return string
*/
public function getCorreoUsuario() {
return $this->correoUsuario;
}
/**
* Set validadocorreo
*
* #param string $validadocorreo
*
* #return Inscritos
*/
public function setValidadocorreo($validadocorreo) {
$this->validadocorreo = $validadocorreo;
return $this;
}
/**
* Get validadocorreo
*
* #return string
*/
public function getValidadocorreo() {
return $this->validadocorreo;
}
/**
* Set tipodocumento
*
* #param string $tipodocumento
*
* #return Inscritos
*/
public function setTipodocumento($tipodocumento) {
$this->tipodocumento = $tipodocumento;
return $this;
}
/**
* Get tipodocumento
*
* #return string
*/
public function getTipodocumento() {
return $this->tipodocumento;
}
/**
* Set documento
*
* #param string $documento
*
* #return Inscritos
*/
public function setDocumento($documento) {
$this->documento = $documento;
return $this;
}
/**
* Get documento
*
* #return string
*/
public function getDocumento() {
return $this->documento;
}
/**
* Set fechanacimiento
*
* #param \DateTime $fechanacimiento
*
* #return Inscritos
*/
public function setFechanacimiento($fechanacimiento) {
$this->fechanacimiento = $fechanacimiento;
return $this;
}
/**
* Get fechanacimiento
*
* #return \DateTime
*/
public function getFechanacimiento() {
return $this->fechanacimiento;
}
/**
* Set pais
*
* #param string $pais
*
* #return Inscritos
*/
public function setPais($pais) {
$this->pais = $pais;
return $this;
}
/**
* Get pais
*
* #return string
*/
public function getPais() {
return $this->pais;
}
/**
* Set provinciaotros
*
* #param string $provinciaotros
*
* #return Inscritos
*/
public function setProvinciaotros($provinciaotros) {
$this->provinciaotros = $provinciaotros;
return $this;
}
/**
* Get provinciaotros
*
* #return string
*/
public function getProvinciaotros() {
return $this->provinciaotros;
}
/**
* Set municipiootros
*
* #param string $municipiootros
*
* #return Inscritos
*/
public function setMunicipiootros($municipiootros) {
$this->municipiootros = $municipiootros;
return $this;
}
/**
* Get municipiootros
*
* #return string
*/
public function getMunicipiootros() {
return $this->municipiootros;
}
/**
* Set codigopostal
*
* #param string $codigopostal
*
* #return Inscritos
*/
public function setCodigopostal($codigopostal) {
$this->codigopostal = $codigopostal;
return $this;
}
/**
* Get codigopostal
*
* #return string
*/
public function getCodigopostal() {
return $this->codigopostal;
}
/**
* Set direccion
*
* #param string $direccion
*
* #return Inscritos
*/
public function setDireccion($direccion) {
$this->direccion = $direccion;
return $this;
}
/**
* Get direccion
*
* #return string
*/
public function getDireccion() {
return $this->direccion;
}
/**
* Set lugarparticipacion
*
* #param string $lugarparticipacion
*
* #return Inscritos
*/
public function setLugarparticipacion($lugarparticipacion) {
$this->lugarparticipacion = $lugarparticipacion;
return $this;
}
/**
* Get lugarparticipacion
*
* #return string
*/
public function getLugarparticipacion() {
return $this->lugarparticipacion;
}
/**
* Set fechainscritpcion
*
* #param \DateTime $fechainscritpcion
*
* #return Inscritos
*/
public function setFechainscritpcion($fechainscritpcion) {
$this->fechainscritpcion = $fechainscritpcion;
return $this;
}
/**
* Get fechainscritpcion
*
* #return \DateTime
*/
public function getFechainscritpcion() {
return $this->fechainscritpcion;
}
/**
* Set ipinscripcion
*
* #param string $ipinscripcion
*
* #return Inscritos
*/
public function setIpinscripcion($ipinscripcion) {
$this->ipinscripcion = $ipinscripcion;
return $this;
}
/**
* Get ipinscripcion
*
* #return string
*/
public function getIpinscripcion() {
return $this->ipinscripcion;
}
/**
* Set cadenaseg
*
* #param string $cadenaseg
*
* #return Inscritos
*/
public function setCadenaseg($cadenaseg) {
$this->cadenaseg = $cadenaseg;
return $this;
}
/**
* Get cadenaseg
*
* #return string
*/
public function getCadenaseg() {
return $this->cadenaseg;
}
/**
* Set bloqueo
*
* #param string $bloqueo
*
* #return Inscritos
*/
public function setBloqueo($bloqueo) {
$this->bloqueo = $bloqueo;
return $this;
}
/**
* Get bloqueo
*
* #return string
*/
public function getBloqueo() {
return $this->bloqueo;
}
/**
* Set razonBloqueo
*
* #param string $razonBloqueo
*
* #return Inscritos
*/
public function setRazonBloqueo($razonBloqueo) {
$this->razonBloqueo = $razonBloqueo;
return $this;
}
/**
* Get razonBloqueo
*
* #return string
*/
public function getRazonBloqueo() {
return $this->razonBloqueo;
}
/**
* Set perfil
*
* #param string $perfil
*
* #return Inscritos
*/
public function setPerfil($perfil) {
$this->perfil = $perfil;
return $this;
}
/**
* Get perfil
*
* #return string
*/
public function getPerfil() {
return $this->perfil;
}
/**
* Set fechaControl
*
* #param \DateTime $fechaControl
*
* #return Inscritos
*/
public function setFechaControl($fechaControl) {
$this->fechaControl = $fechaControl;
return $this;
}
/**
* Get fechaControl
*
* #return \DateTime
*/
public function getFechaControl() {
return $this->fechaControl;
}
/**
* Set idMunicipio
*
* #param integer $idMunicipio
*
* #return Inscritos
*/
public function setIdMunicipio($idMunicipio) {
$this->idMunicipio = $idMunicipio;
return $this;
}
/**
* Get idMunicipio
*
* #return integer
*/
public function getIdMunicipio() {
return $this->idMunicipio;
}
/**
* Set idProvincia
*
* #param integer $idProvincia
*
* #return Inscritos
*/
public function setIdProvincia($idProvincia) {
$this->idProvincia = $idProvincia;
return $this;
}
/**
* Get idProvincia
*
* #return integer
*/
public function getIdProvincia() {
return $this->idProvincia;
}
/**
* Set idCcaa
*
* #param string $idCcaa
*
* #return Inscritos
*/
public function setIdCcaa($idCcaa) {
$this->idCcaa = $idCcaa;
return $this;
}
/**
* Get idCcaa
*
* #return string
*/
public function getIdCcaa() {
return $this->idCcaa;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $imagenes;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $validaInscritos;
/**
* #var \BackendBundle\Entity\Ccaa
*/
private $ccaaInscritos;
/**
* #var \BackendBundle\Entity\Municipios
*/
private $municipioInscritos;
/**
* #var \BackendBundle\Entity\Provincia
*/
private $provinciaInscritos;
/**
* Constructor
*/
public function __construct() {
$this->imagenes = new \Doctrine\Common\Collections\ArrayCollection();
$this->validaInscritos = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add imagene
*
* #param \BackendBundle\Entity\InscritosImages $imagene
*
* #return Inscritos
*/
public function addImagene(\BackendBundle\Entity\InscritosImages $imagene) {
$this->imagenes[] = $imagene;
return $this;
}
/**
* Remove imagene
*
* #param \BackendBundle\Entity\InscritosImages $imagene
*/
public function removeImagene(\BackendBundle\Entity\InscritosImages $imagene) {
$this->imagenes->removeElement($imagene);
}
/**
* Get imagenes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getImagenes() {
return $this->imagenes;
}
/**
* Add validaInscrito
*
* #param \BackendBundle\Entity\ValidaInscritos $validaInscrito
*
* #return Inscritos
*/
public function addValidaInscrito(\BackendBundle\Entity\ValidaInscritos $validaInscrito) {
$this->validaInscritos[] = $validaInscrito;
return $this;
}
/**
* Remove validaInscrito
*
* #param \BackendBundle\Entity\ValidaInscritos $validaInscrito
*/
public function removeValidaInscrito(\BackendBundle\Entity\ValidaInscritos $validaInscrito) {
$this->validaInscritos->removeElement($validaInscrito);
}
/**
* Get validaInscritos
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getValidaInscritos() {
return $this->validaInscritos;
}
/**
* Set ccaaInscritos
*
* #param \BackendBundle\Entity\Ccaa $ccaaInscritos
*
* #return Inscritos
*/
public function setCcaaInscritos(\BackendBundle\Entity\Ccaa $ccaaInscritos = null) {
$this->ccaaInscritos = $ccaaInscritos;
return $this;
}
/**
* Get ccaaInscritos
*
* #return \BackendBundle\Entity\Ccaa
*/
public function getCcaaInscritos() {
return $this->ccaaInscritos;
}
/**
* Set municipioInscritos
*
* #param \BackendBundle\Entity\Municipios $municipioInscritos
*
* #return Inscritos
*/
public function setMunicipioInscritos(\BackendBundle\Entity\Municipios $municipioInscritos = null) {
$this->municipioInscritos = $municipioInscritos;
return $this;
}
/**
* Get municipioInscritos
*
* #return \BackendBundle\Entity\Municipios
*/
public function getMunicipioInscritos() {
return $this->municipioInscritos;
}
/**
* Set provinciaInscritos
*
* #param \BackendBundle\Entity\Provincia $provinciaInscritos
*
* #return Inscritos
*/
public function setProvinciaInscritos(\BackendBundle\Entity\Provincia $provinciaInscritos = null) {
$this->provinciaInscritos = $provinciaInscritos;
return $this;
}
/**
* Get provinciaInscritos
*
* #return \BackendBundle\Entity\Provincia
*/
public function getProvinciaInscritos() {
return $this->provinciaInscritos;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $inscritosAcciones;
/**
* Add inscritosAccione
*
* #param \BackendBundle\Entity\InscritosAcciones $inscritosAccione
*
* #return Inscritos
*/
public function addInscritosAccione(\BackendBundle\Entity\InscritosAcciones $inscritosAccione) {
$this->inscritosAcciones[] = $inscritosAccione;
return $this;
}
/**
* Remove inscritosAccione
*
* #param \BackendBundle\Entity\InscritosAcciones $inscritosAccione
*/
public function removeInscritosAccione(\BackendBundle\Entity\InscritosAcciones $inscritosAccione) {
$this->inscritosAcciones->removeElement($inscritosAccione);
}
/**
* Get inscritosAcciones
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getInscritosAcciones() {
return $this->inscritosAcciones;
}
}
entity InscritosAcciones
namespace BackendBundle\Entity;
/**
* InscritosAcciones
*/
class InscritosAcciones
{
/**
* #var integer
*/
private $id;
/**
* #var integer
*/
private $status;
/**
* #var string
*/
private $accion;
/**
* #var string
*/
private $datos;
/**
* #var \DateTime
*/
private $fecha = 'CURRENT_TIMESTAMP';
/**
* #var integer
*/
private $inscritosId;
/**
* #var \BackendBundle\Entity\Inscritos
*/
private $inscritos;
/**
* #var \BackendBundle\Entity\Acciones
*/
private $acciones;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set status
*
* #param integer $status
*
* #return InscritosAcciones
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set accion
*
* #param string $accion
*
* #return InscritosAcciones
*/
public function setAccion($accion)
{
$this->accion = $accion;
return $this;
}
/**
* Get accion
*
* #return string
*/
public function getAccion()
{
return $this->accion;
}
/**
* Set datos
*
* #param string $datos
*
* #return InscritosAcciones
*/
public function setDatos($datos)
{
$this->datos = $datos;
return $this;
}
/**
* Get datos
*
* #return string
*/
public function getDatos()
{
return $this->datos;
}
/**
* Set fecha
*
* #param \DateTime $fecha
*
* #return InscritosAcciones
*/
public function setFecha($fecha)
{
$this->fecha = $fecha;
return $this;
}
/**
* Get fecha
*
* #return \DateTime
*/
public function getFecha()
{
return $this->fecha;
}
/**
* Set inscritosId
*
* #param integer $inscritosId
*
* #return InscritosAcciones
*/
public function setInscritosId($inscritosId)
{
$this->inscritosId = $inscritosId;
return $this;
}
/**
* Get inscritosId
*
* #return integer
*/
public function getInscritosId()
{
return $this->inscritosId;
}
/**
* Set inscritos
*
* #param \BackendBundle\Entity\Inscritos $inscritos
*
* #return InscritosAcciones
*/
public function setInscritos(\BackendBundle\Entity\Inscritos $inscritos = null)
{
$this->inscritos = $inscritos;
return $this;
}
/**
* Get inscritos
*
* #return \BackendBundle\Entity\Inscritos
*/
public function getInscritos()
{
return $this->inscritos;
}
/**
* Set acciones
*
* #param \BackendBundle\Entity\Acciones $acciones
*
* #return InscritosAcciones
*/
public function setAcciones(\BackendBundle\Entity\Acciones $acciones = null)
{
$this->acciones = $acciones;
return $this;
}
/**
* Get acciones
*
* #return \BackendBundle\Entity\Acciones
*/
public function getAcciones()
{
return $this->acciones;
}
}
Both tables are related to other tables but are not necessary in this query. The incritosAcciones table is related to a table of actions, and the one of inscribed with enough tables since it is a quite complex structure.
Regarding what result gives me, because I think I had previously put it, I list all the rows of the inscribed table since they will always have more shares (something in the status field) besides the status = 8
Finally, if in the consultation I group it by
->groupBy("u.status")
I only get (normal) one record for each of the statuses except the one that has status 8
a full consultation would be
$query = $em->createQueryBuilder()
->from("BackendBundle:Inscritos", "e")
->select("e")
->innerJoin("BackendBundle:InscritosAcciones", "u", "WITH", "e.id=u.inscritosId")
->groupBy("u.status")
->where("u.status != 8")
->getQuery();
I have added two screenshots of my phpmyAdmin that you can see in the Spanish version because here I do not have enough reputation to upload images
https://es.stackoverflow.com/questions/132649/problema-para-que-no-salga-un-usuario-en-consulta-onetomany-si-se-da-una-condici
And what they would have to leave are users 43 and 63, nothing would happen because the other users left who do not have any action yet, but the one who should never leave is user 1, who has an action with status 8
Can someone help me please.
Thank you
I'm using easyadmin and fosuserbundle.
The problém that everytime i try to update(change) the user password , nothing is happen , the same old password still the same. I think maybe i miss some config .
Config.yml
easyadmin:
Admin:
class: AppBundle\Entity\User
form:
fields:
- username
- email
- { property: 'plainPassword' , type: 'text'}
User.php:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Security\Core\Util\SecureRandom;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
/**
* #Vich\Uploadable
* #ORM\Entity()
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="user")
*
* #UniqueEntity("email")
*
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255,nullable=true)
*
*/
public $nom;
/**
* #ORM\Column(type="string",nullable=true,length=255,nullable=true)
*/
public $prenom;
/**
* #ORM\Column(type="string",nullable=true,length=255,nullable=true)
*/
public $adresse;
/**
* #ORM\Column(type="string", length=255,nullable=true)
*
* #Assert\Range(
* min = 00000000,
* max = 99999999,minMessage="Entrer un numero de cin correct svp",maxMessage="Entrer un numero tel correct svp"
* )
*/
protected $phone;
/**
* #var Devise[]
*
* #ORM\OneToMany(targetEntity="Devise", mappedBy="buyer")
*/
private $purchases;
/**
* The creation date of the product.
*
* #var \DateTime
* #ORM\Column(type="datetime", name="created_at")
*/
private $createdAt = null;
public function __construct()
{
parent::__construct();
// your own logic
$this->purchases = new ArrayCollection();
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set referance
*
* #param string $referance
*
*/
public function setReferance($referance )
{if($this->referance==NULL) $referance ='2';
$this->referance = $referance ;
return $this;
}
/**
* Get referance
*
* #return string
*/
public function getReferance ()
{
return $this->referance ;
}
/**
* Set forename
*
* #param string $forname
* #return User
*/
public function setForename($forename)
{
$this->forname = $forename;
return $this;
}
/**
* Get forename
*
* #return string
*/
public function getForename()
{
return $this->forname;
}
/**
* Asks whether the user is granted a particular role
*
* #return boolean
*/
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
/**
* Set nickname
*
* #param string $nickname
* #return User
*/
public function setNickname($nickname)
{
$this->nickname = $nickname;
return $this;
}
/**
* Get nickname
*
* #return string
*/
public function getNickname()
{
return $this->nickname;
}
/**
* Set lastEdited
*
* #param \DateTime $lastEdited
* #return User
*/
public function setLastEdited($lastEdited)
{
$this->lastEdited = $lastEdited;
return $this;
}
/**
* Get lastEdited
*
* #return \DateTime
*/
public function getLastEdited()
{
return $this->lastEdited;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function setLastEditedValueAsNow() {
$this->setLastEdited(new \DateTime());
}
/**
* Set surname
*
* #param string $surname
* #return User
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* #return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
*
* #return Utilisateurs
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
public function __toString()
{if ($this->prenom != null && $this->nom!= null && $this->phone != null) {
return 'prenom&nom :'.$this->prenom.' '.$this->nom.' | phone : '.$this->phone ;
}
else return 'id :'.$this->id.' | username : '.$this->username ; }
/**
* Set nom
*
* #param string $nom
*
* #return Utilisateurs
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
*
* #return Utilisateurs
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set ville
*
* #param string $ville
*
* #return Utilisateurs
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* #return string
*/
public function getVille()
{
return $this->ville;
}
/**
* Set class
*
* #param string $class
*
* #return Utilisateurs
*/
public function setClass($class)
{
$this->class = $class;
return $this;
}
/**
* Get class
*
* #return string
*/
public function getClass()
{
return $this->class;
}
/**
* Set phone
*
* #param string $phone
*
* #return Utilisateurs
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Add purchase
*
* #param \AppBundle\Entity\Devise $purchase
*
* #return User
*/
public function addPurchase(\AppBundle\Entity\Devise $purchase)
{
$this->purchases[] = $purchase;
return $this;
}
/**
* Remove purchase
*
* #param \AppBundle\Entity\Devise $purchase
*/
public function removePurchase(\AppBundle\Entity\Devise $purchase)
{
$this->purchases->removeElement($purchase);
}
/**
* Get purchases
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPurchases()
{
return $this->purchases;
}
/**
* Set adresse
*
* #param string $adresse
*
* #return User
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return User
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
));
}
public function unserialize($serialized)
{
list(
$this->id,
$this->username,
$this->password) = unserialize($serialized);
}
}
Symfony3 with PhpStorm.2016.3.2
I succeeded in making a file uploader for one picture only. But now I need to make it "multiple"
I will show you the code and the error that comes up with it as I canno't upload multiple files.
here is the controller
public function newAction(Request $request)
{
$restaurant = new Restaurant();
$form = $this->createForm(RestaurantType::class, $restaurant);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
// file upload
if ($request->files->get('restaurant')['picture'] != null) {
$file = $request->files->get('restaurant')['picture'];
$targetDir = $this->getParameter('uploaded_restaurants');
$filename = $this->get('app.uploader')->upload($file, $targetDir);
$mediaRestaurant = null;
if ($restaurant->getId() != null) {
$mediaRestaurant = $this->getDoctrine()->getRepository('AppBundle:Media')->findPictureByRestaurant($restaurant);
}
if ($mediaRestaurant) {
$media = $mediaRestaurant;
$fs = new Filesystem();
try {
$fs->remove($this->get('kernel')->getRootDir().'/../web/uploads/restaurants/'.$media->getName());
} catch (IOException $e) {
echo "error";
}
} else {
$media = new Media();
$media->setCreatedAt(new \DateTime());
}
$originalName = $file->getClientOriginalName();
$media->setName($filename)
->setOriginalName($originalName)
->setType('img')
->setContext('restaurant_picture')
->setUpdatedAt(new \DateTime())
;
$media->setRestaurant($restaurant);
$em->persist($media);
}
$restaurant->setIsActivated(false);
$em->persist($restaurant);
$em->flush();
}
return $this->render('admin/restaurant/new.html.twig', array(
'restaurant' => $restaurant,
'form' => $form->createView(),
));
}
my FormType(called RestaurantType) where I added a field for file upload (when I set up multiple to false it actually works for only one picture)
$builder
->add('picture', FileType::class, array(
'label' => 'Photos du restaurant',
'multiple' => true,
'required' => false,
'mapped' => false,
'attr' => array(
'accept' => '.jpg,.jpeg,.png'),
))
The service to uploads file
class FileUploader
{
/**
* #param UploadedFile $file
* #param $targetDir
* #return string
*/
public function upload(UploadedFile $file, $targetDir)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($targetDir, $fileName);
return $fileName;
}
}
the queryBuilder in the MediaRepository
public function findPictureByRestaurant(Restaurant $restaurant)
{
return $this->createQueryBuilder('m')
->select('m')
->where('m.restaurant = :restaurant')
->setParameter('restaurant', $restaurant)
->andWhere('m.context = :restaurant_picture')
->setParameter('restaurant_picture', 'restaurant_picture')
->getQuery()
->getOneOrNullResult();
}
in my show.html.twig where you can see the picture
{% if restaurant.medias != null and restaurant.medias.count > 0 and restaurant.medias[0].name != null %}
<img src="/uploads/restaurants/{{ restaurant.medias[0].name }}">
{% endif %}
my config.yml where the files are uploaded
parameters:
locale: fr
uploaded_restaurants: "%kernel.root_dir%/../web/uploads/restaurants"
And the entity Restaurant which is pretty long (sorry)
/**
* Restaurant
*
* #ORM\Table(name="restaurant")
* #ORM\Entity(repositoryClass="AppBundle\Repository\RestaurantRepository")
*/
class Restaurant
{
/**
* #var FoodType
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\FoodType", inversedBy="restaurants")
* #ORM\JoinColumn(name="food_type_id", referencedColumnName="id")
*/
private $foodType;
/**
* #var City
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\City", inversedBy="restaurants")
* #ORM\JoinColumn(name="city_id", referencedColumnName="id")
*/
private $city;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Media", mappedBy="restaurant")
*/
private $medias;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Privatisation", mappedBy="restaurant")
*/
private $privatisations;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Retrocession", mappedBy="restaurant")
*/
private $retrocessions;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\OpenedSlot", mappedBy="restaurant")
*/
private $openedSlots;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\ExceptionSlot", mappedBy="restaurant")
*/
private $exceptionSlots;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Slot", mappedBy="restaurant")
*/
private $slots;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Chef", mappedBy="restaurant")
*/
private $chefs;
/**
* Constructor
*/
public function __construct()
{
$this->medias = new ArrayCollection();
$this->privatisations = new ArrayCollection();
$this->retrocessions = new ArrayCollection();
$this->openedSlots = new ArrayCollection();
$this->exceptionSlots = new ArrayCollection();
$this->slots = new ArrayCollection();
$this->chefs = new ArrayCollection();
}
/**
* #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=120, unique=true)
* #Assert\Length(
* max = 120,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255, unique=true)
* #Gedmo\Slug(fields={"name"})
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="webUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $webUrl;
/**
* #var string
*
* #ORM\Column(name="tripAdvisorUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $tripAdvisorUrl;
/**
* #var string
*
* #ORM\Column(name="facebookUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $facebookUrl;
/**
* #var string
*
* #ORM\Column(name="twitterUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $twitterUrl;
/**
* #var string
*
* #ORM\Column(name="instagramUrl", type="string", length=255, nullable=true)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $instagramUrl;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=20)
* #Assert\Regex(
* pattern="#^0[1-9]([-. ]?[0-9]{2}){4}$#",
* match=true,
* message="Numéro de téléphone invalide."
* )
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="phone2", type="string", length=20, nullable=true)
* #Assert\Regex(
* pattern="#^0[1-9]([-. ]?[0-9]{2}){4}$#",
* match=true,
* message="Numéro de téléphone invalide."
* )
*/
private $phone2;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $email;
/**
* #var float
*
* #ORM\Column(name="latitude", type="float")
* #Assert\Regex(
* pattern="/^-?(?:\d+|\d*\.\d+)$/",
* match=true,
* )
*/
private $latitude;
/**
* #var float
*
* #ORM\Column(name="longitude", type="float")
* #Assert\Regex(
* pattern="/^-?(?:\d+|\d*\.\d+)$/",
* match=true,
* )
*/
private $longitude;
/**
* #var int
*
* #ORM\Column(name="stars", type="integer", nullable=true)
* #Assert\Regex(
* pattern="/^[0-9]+$/",
* match=true,
* message="Ceci n'est pas un chiffre."
* )
*/
private $stars;
/**
* #var int
*
* #ORM\Column(name="seatNumber", type="integer", nullable=true)
* #Assert\Regex(
* pattern="/^[0-9]+$/",
* match=true,
* )
*/
private $seatNumber;
/**
* #var float
*
* #ORM\Column(name="minPrice", type="float", nullable=true)
* #Assert\Regex(
* pattern="/^-?(?:\d+|\d*\.\d+)$/",
* match=true,
* )
*/
private $minPrice;
/**
* #var float
*
* #ORM\Column(name="maxPrice", type="float", nullable=true)
* #Assert\Regex(
* pattern="/^-?(?:\d+|\d*\.\d+)$/",
* match=true,
* )
*/
private $maxPrice;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
* #Assert\Length(
* max = 255,
* maxMessage = "Ce champ ne peut pas dépasser {{ limit }} caractères."
* )
*/
private $address;
/**
* #var bool
*
* #ORM\Column(name="is_activated", type="boolean")
*/
private $isActivated = true;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Restaurant
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set slug
*
* #param string $slug
*
* #return Restaurant
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set description
*
* #param string $description
*
* #return Restaurant
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set webUrl
*
* #param string $webUrl
*
* #return Restaurant
*/
public function setWebUrl($webUrl)
{
$this->webUrl = $webUrl;
return $this;
}
/**
* Get webUrl
*
* #return string
*/
public function getWebUrl()
{
return $this->webUrl;
}
/**
* Set tripAdvisorUrl
*
* #param string $tripAdvisorUrl
*
* #return Restaurant
*/
public function setTripAdvisorUrl($tripAdvisorUrl)
{
$this->tripAdvisorUrl = $tripAdvisorUrl;
return $this;
}
/**
* Get tripAdvisorUrl
*
* #return string
*/
public function getTripAdvisorUrl()
{
return $this->tripAdvisorUrl;
}
/**
* Set facebookUrl
*
* #param string $facebookUrl
*
* #return Restaurant
*/
public function setFacebookUrl($facebookUrl)
{
$this->facebookUrl = $facebookUrl;
return $this;
}
/**
* Get facebookUrl
*
* #return string
*/
public function getFacebookUrl()
{
return $this->facebookUrl;
}
/**
* Set twitterUrl
*
* #param string $twitterUrl
*
* #return Restaurant
*/
public function setTwitterUrl($twitterUrl)
{
$this->twitterUrl = $twitterUrl;
return $this;
}
/**
* Get twitterUrl
*
* #return string
*/
public function getTwitterUrl()
{
return $this->twitterUrl;
}
/**
* Set instagramUrl
*
* #param string $instagramUrl
*
* #return Restaurant
*/
public function setInstagramUrl($instagramUrl)
{
$this->instagramUrl = $instagramUrl;
return $this;
}
/**
* Get instagramUrl
*
* #return string
*/
public function getInstagramUrl()
{
return $this->instagramUrl;
}
/**
* Set phone
*
* #param string $phone
*
* #return Restaurant
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set phone2
*
* #param string $phone2
*
* #return Restaurant
*/
public function setPhone2($phone2)
{
$this->phone2 = $phone2;
return $this;
}
/**
* Get phone2
*
* #return string
*/
public function getPhone2()
{
return $this->phone2;
}
/**
* Set email
*
* #param string $email
*
* #return Restaurant
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set latitude
*
* #param float $latitude
*
* #return Restaurant
*/
public function setLatitude($latitude)
{
$this->latitude = $latitude;
return $this;
}
/**
* Get latitude
*
* #return float
*/
public function getLatitude()
{
return $this->latitude;
}
/**
* Set longitude
*
* #param float $longitude
*
* #return Restaurant
*/
public function setLongitude($longitude)
{
$this->longitude = $longitude;
return $this;
}
/**
* Get longitude
*
* #return float
*/
public function getLongitude()
{
return $this->longitude;
}
/**
* Set stars
*
* #param integer $stars
*
* #return Restaurant
*/
public function setStars($stars)
{
$this->stars = $stars;
return $this;
}
/**
* Get stars
*
* #return int
*/
public function getStars()
{
return $this->stars;
}
/**
* Set seatNumber
*
* #param integer $seatNumber
*
* #return Restaurant
*/
public function setSeatNumber($seatNumber)
{
$this->seatNumber = $seatNumber;
return $this;
}
/**
* Get seatNumber
*
* #return int
*/
public function getSeatNumber()
{
return $this->seatNumber;
}
/**
* Set minPrice
*
* #param float $minPrice
*
* #return Restaurant
*/
public function setMinPrice($minPrice)
{
$this->minPrice = $minPrice;
return $this;
}
/**
* Get minPrice
*
* #return float
*/
public function getMinPrice()
{
return $this->minPrice;
}
/**
* Set maxPrice
*
* #param float $maxPrice
*
* #return Restaurant
*/
public function setMaxPrice($maxPrice)
{
$this->maxPrice = $maxPrice;
return $this;
}
/**
* Get maxPrice
*
* #return float
*/
public function getMaxPrice()
{
return $this->maxPrice;
}
/**
* Set address
*
* #param string $address
*
* #return Restaurant
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Add media
*
* #param Media $media
*
* #return Restaurant
*/
public function addMedia(Media $media)
{
$this->medias[] = $media;
return $this;
}
/**
* Remove media
*
* #param Media $media
*/
public function removeMedia(Media $media)
{
$this->medias->removeElement($media);
}
/**
* Get medias
*
* #return ArrayCollection
*/
public function getMedias()
{
return $this->medias;
}
/**
* Set foodType
*
* #param FoodType $foodType
*
* #return Restaurant
*/
public function setFoodType(FoodType $foodType = null)
{
$this->foodType = $foodType;
return $this;
}
/**
* Get foodType
*
* #return FoodType
*/
public function getFoodType()
{
return $this->foodType;
}
/**
* Add privatisation
*
* #param Privatisation $privatisation
*
* #return Restaurant
*/
public function addPrivatisation(Privatisation $privatisation)
{
$this->privatisations[] = $privatisation;
return $this;
}
/**
* Remove privatisation
*
* #param Privatisation $privatisation
*/
public function removePrivatisation(Privatisation $privatisation)
{
$this->privatisations->removeElement($privatisation);
}
/**
* Get privatisations
*
* #return ArrayCollection
*/
public function getPrivatisations()
{
return $this->privatisations;
}
/**
* Add retrocession
*
* #param Retrocession $retrocession
*
* #return Restaurant
*/
public function addRetrocession(Retrocession $retrocession)
{
$this->retrocessions[] = $retrocession;
return $this;
}
/**
* Remove retrocession
*
* #param Retrocession $retrocession
*/
public function removeRetrocession(Retrocession $retrocession)
{
$this->retrocessions->removeElement($retrocession);
}
/**
* Get retrocessions
*
* #return ArrayCollection
*/
public function getRetrocessions()
{
return $this->retrocessions;
}
/**
* Add openedSlot
*
* #param OpenedSlot $openedSlot
*
* #return Restaurant
*/
public function addOpenedSlot(OpenedSlot $openedSlot)
{
$this->openedSlots[] = $openedSlot;
return $this;
}
/**
* Remove openedSlot
*
* #param OpenedSlot $openedSlot
*/
public function removeOpenedSlot(OpenedSlot $openedSlot)
{
$this->openedSlots->removeElement($openedSlot);
}
/**
* Get openedSlots
*
* #return ArrayCollection
*/
public function getOpenedSlots()
{
return $this->openedSlots;
}
/**
* Add exceptionSlot
*
* #param ExceptionSlot $exceptionSlot
*
* #return Restaurant
*/
public function addExceptionSlot(ExceptionSlot $exceptionSlot)
{
$this->exceptionSlots[] = $exceptionSlot;
return $this;
}
/**
* Remove exceptionSlot
*
* #param ExceptionSlot $exceptionSlot
*/
public function removeExceptionSlot(ExceptionSlot $exceptionSlot)
{
$this->exceptionSlots->removeElement($exceptionSlot);
}
/**
* Get exceptionSlots
*
* #return ArrayCollection
*/
public function getExceptionSlots()
{
return $this->exceptionSlots;
}
/**
* Add slot
*
* #param Slot $slot
*
* #return Restaurant
*/
public function addSlot(Slot $slot)
{
$this->slots[] = $slot;
return $this;
}
/**
* Remove slot
*
* #param Slot $slot
*/
public function removeSlot(Slot $slot)
{
$this->slots->removeElement($slot);
}
/**
* Get slots
*
* #return ArrayCollection
*/
public function getSlots()
{
return $this->slots;
}
/**
* Add chef
*
* #param Chef $chef
*
* #return Restaurant
*/
public function addChef(Chef $chef)
{
$this->chefs[] = $chef;
return $this;
}
/**
* Remove chef
*
* #param Chef $chef
*/
public function removeChef(Chef $chef)
{
$this->chefs->removeElement($chef);
}
/**
* Get chefs
*
* #return ArrayCollection
*/
public function getChefs()
{
return $this->chefs;
}
/**
* Set city
*
* #param City $city
*
* #return Restaurant
*/
public function setCity(City $city = null)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* #return City
*/
public function getCity()
{
return $this->city;
}
/**
* #return bool
*/
public function getIsActivated()
{
return $this->isActivated;
}
/**
* #param bool $isActivated
*/
public function setIsActivated($isActivated)
{
$this->isActivated = $isActivated;
}
}
and the error that comes up when I upload a picture and click on submit button
To sum up it up all, this code works for only one picture when I set up multiple to false in my FormType. But then I am stuck for the multiple file upload and I can't get to find a way around that. Does someone know how to handle it with the code I given you?
Thank you
Because your file definition accept multiple uploads, you need to modify upload part of your controller:
// file upload
if ($request->files->get('restaurant')['picture'] != null) {
$files = $request->files->get('restaurant')['picture'];
foreach ($files as $file) {
$targetDir = $this->getParameter('uploaded_restaurants');
$filename = $this->get('app.uploader')->upload($file, $targetDir);
$mediaRestaurant = null;
if ($restaurant->getId() != null) {
$mediaRestaurant = $this->getDoctrine()->getRepository('AppBundle:Media')->findPictureByRestaurant($restaurant);
}
if ($mediaRestaurant) {
$media = $mediaRestaurant;
$fs = new Filesystem();
try {
$fs->remove($this->get('kernel')->getRootDir().'/../web/uploads/restaurants/'.$media->getName());
} catch (IOException $e) {
echo "error";
}
} else {
$media = new Media();
$media->setCreatedAt(new \DateTime());
}
$originalName = $file->getClientOriginalName();
$media->setName($filename)
->setOriginalName($originalName)
->setType('img')
->setContext('restaurant_picture')
->setUpdatedAt(new \DateTime())
;
$media->setRestaurant($restaurant);
$em->persist($media);
}
}
Notify that I've taken all files from form uploaded data first, and run your code in a foreach loop.
You need to handle an array in your upload method, as itll get that from the form, rather than an individual UploadedFile object.
/**
* #param UploadedFile $file
* #param $targetDir
* #return array
*/
public function upload($files, $targetDir)
{
if(!is_array($files)) {
$files = (array) $files; // cast to array in case of a form that isn't multiple.
}
$filenames = [];
foreach($files as $file) {
$filenames[] = md5(uniqid()).'.'.$file->guessExtension();
$file->move($targetDir, $fileName);
}
return $filenames;
}
youll need to twiddle whatever is getting the return filename variable, as it'll now be an array.
The other way, which in my opinion is a better UX, is to use a CollectionType and render a file input box per file. Heres a quick example.
$builder->add('file_uploads', CollectionType::class, [
'entry_type' => FileType::class,
'entry_options' => [
'label' => 'Photos du restaurant',
'multiple' => true,
'required' => false,
'mapped' => false,
'attr' => [
'accept' => '.jpg,.jpeg,.png',
],
'allow_add' => true,
'allow_delete' => true,
],
'prototype' => true,
]);
Youll then need to handle the resulting ArrayCollection in your upload handler. But this gives a much nicer interface for the user.
Ive not tested this snippet, so you might have to debug or adapt it to fit with what you're doing.
When I try to delete or clear rates of courier company it throws out following error. I think I don't have good debugging skills. Can anybody help me, what is the reason behind this? Here is controller, view and modal.
Entity has to be managed or scheduled for removal for single computation Sokosimu\PostalDeliveryBundle\Entity\PostalCharge#0000000059f7113c00000000372b1d9d
Controller
public function clearRatesAction(DeliveryCompany $deliveryCompany){
$em = $this->get('doctrine')->getManager();
$postalcharge = new PostalCharge();
$em->getConnection()->beginTransaction();
try {
$rate = $postalcharge ->setDeliveryCompany($deliveryCompany);
$em->persist($rate);
$em->remove($rate);
$em->flush($rate);
$em->getConnection()->commit();
} catch(Exception $e){
$em->getConnection()->rollback();
throw $e;
}
return $this->redirect($this->generateUrl('sokosimu_postal_delivery_list_company'));
}
}
Twig (Views)
<tbody>
{% for deliveryCompany in deliveryCompanyList %}
<tr>
<td><a href="{{ path('sokosimu_postal_delivery_company_detail',{'deliveryCompany':deliveryCompany.getid()}) }}">{{ deliveryCompany.getName() }}</td>
<td>{{ deliveryCompany.getAddress() }}</td>
<td>Edit
ClearRates
</td>
</tr>
{% endfor %}
</tbody>
Postal charge entity
<?php
// src/Sokosimu/PostalDeliveryBundle/Entity/PostalCharge.php
namespace Sokosimu\PostalDeliveryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/** * #ORM\Entity(repositoryClass="Sokosimu\PostalDeliveryBundle\Entity\Repository\PostalChargeRepository")
* #ORM\Table(name="postal_charge")
* #ORM\HasLifecycleCallbacks()
*/
class PostalCharge
{
/**
* #ORM\Id
* #ORM\Column(name="id",type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="record_type",type="string", length=225)
*/
protected $recordType;
/**
* #ORM\Column(name="active_from",type="datetime", nullable=True)
*/
protected $activeFrom;
/**
* #ORM\Column(name="active_to",type="datetime", nullable=True)
*/
protected $activeTo;
/**
* #ORM\Column(name="active_record",type="string", length=225, nullable=True)
*/
protected $activeRecord;
/**
* #ORM\Column(name="origin_country",type="string", length=225, nullable=True)
*/
protected $originCountry;
/**
* #ORM\Column(name="weight_from",type="integer")
*/
protected $weightFrom;
/**
* #ORM\Column(name="weight_to",type="integer")
*/
protected $weightTo;
/**
* #ORM\Column(name="from_region",type="string", length=225, nullable=True)
*/
protected $fromRegion;
/**
* #ORM\Column(name="to_region",type="string", length=225, nullable=True)
*/
protected $toRegion;
/**
* #ORM\Column(name="priority",type="string", length=225, nullable=True)
*/
protected $priority;
/**
* #ORM\Column(name="economy",type="string", length=225, nullable=True)
*/
protected $economy;
/**
* #ORM\Column(name="increment_price",type="string", length=225, nullable=True)
*/
protected $incrementPrice;
/**
* #ORM\Column(name="tax",type="string", length=225, nullable=True)
*/
protected $tax;
/**
* #ORM\Column(name="insurance",type="string", length=225, nullable=True)
*/
protected $insurance;
/**
* #ORM\Column(name="increment_unit",type="string", length=225, nullable=True)
*/
protected $incrementUnit;
/**
* #ORM\Column(name="currency_code",type="string", length=225, nullable=True)
*/
protected $currencyCode;
/**
* #ORM\Column(name="country_code",type="string", length=225, nullable=True)
*/
protected $countryCode;
/**
* #ORM\ManyToOne(targetEntity="DeliveryCompany")
* #ORM\JoinColumn(name="delivery_company_id",referencedColumnName="id",nullable=True)
*/
protected $deliveryCompany;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set recordType
*
* #param string $recordType
* #return PostalCharge
*/
public function setRecordType($recordType)
{
$this->recordType = $recordType;
return $this;
}
/**
* Get recordType
*
* #return string
*/
public function getRecordType()
{
return $this->recordType;
}
/**
* Set activeFrom
*
* #param \DateTime $activeFrom
* #return PostalCharge
*/
public function setActiveFrom($activeFrom)
{
$this->activeFrom = $activeFrom;
return $this;
}
/**
* Get activeFrom
*
* #return \DateTime
*/
public function getActiveFrom()
{
return $this->activeFrom;
}
/**
* Set activeTo
*
* #param \DateTime $activeTo
* #return PostalCharge
*/
public function setActiveTo($activeTo)
{
$this->activeTo = $activeTo;
return $this;
}
/**
* Get activeTo
*
* #return \DateTime
*/
public function getActiveTo()
{
return $this->activeTo;
}
/**
* Set activeRecord
*
* #param string $activeRecord
* #return PostalCharge
*/
public function setActiveRecord($activeRecord)
{
$this->activeRecord = $activeRecord;
return $this;
}
/**
* Get activeRecord
*
* #return string
*/
public function getActiveRecord()
{
return $this->activeRecord;
}
/**
* Set originCountry
*
* #param string $originCountry
* #return PostalCharge
*/
public function setOriginCountry($originCountry)
{
$this->originCountry = $originCountry;
return $this;
}
/**
* Get originCountry
*
* #return string
*/
public function getOriginCountry()
{
return $this->originCountry;
}
/**
* Set weightFrom
*
* #param integer $weightFrom
* #return PostalCharge
*/
public function setWeightFrom($weightFrom)
{
$this->weightFrom = $weightFrom;
return $this;
}
/**
* Get weightFrom
*
* #return integer
*/
public function getWeightFrom()
{
return $this->weightFrom;
}
/**
* Set weightTo
*
* #param integer $weightTo
* #return PostalCharge
*/
public function setWeightTo($weightTo)
{
$this->weightTo = $weightTo;
return $this;
}
/**
* Get weightTo
*
* #return integer
*/
public function getWeightTo()
{
return $this->weightTo;
}
/**
* Set fromRegion
*
* #param string $fromRegion
* #return PostalCharge
*/
public function setFromRegion($fromRegion)
{
$this->fromRegion = $fromRegion;
return $this;
}
/**
* Get fromRegion
*
* #return string
*/
public function getFromRegion()
{
return $this->fromRegion;
}
/**
* Set toRegion
*
* #param string $toRegion
* #return PostalCharge
*/
public function setToRegion($toRegion)
{
$this->toRegion = $toRegion;
return $this;
}
/**
* Get toRegion
*
* #return string
*/
public function getToRegion()
{
return $this->toRegion;
}
/**
* Set priority
*
* #param string $priority
* #return PostalCharge
*/
public function setPriority($priority)
{
$this->priority = $priority;
return $this;
}
/**
* Get priority
*
* #return string
*/
public function getPriority()
{
return $this->priority;
}
/**
* Set economy
*
* #param string $economy
* #return PostalCharge
*/
public function setEconomy($economy)
{
$this->economy = $economy;
return $this;
}
/**
* Get economy
*
* #return string
*/
public function getEconomy()
{
return $this->economy;
}
/**
* Set incrementPrice
*
* #param string $incrementPrice
* #return PostalCharge
*/
public function setIncrementPrice($incrementPrice)
{
$this->incrementPrice = $incrementPrice;
return $this;
}
/**
* Get incrementPrice
*
* #return string
*/
public function getIncrementPrice()
{
return $this->incrementPrice;
}
/**
* Set tax
*
* #param string $tax
* #return PostalCharge
*/
public function setTax($tax)
{
$this->tax = $tax;
return $this;
}
/**
* Get tax
*
* #return string
*/
public function getTax()
{
return $this->tax;
}
/**
* Set insurance
*
* #param string $insurance
* #return PostalCharge
*/
public function setInsurance($insurance)
{
$this->insurance = $insurance;
return $this;
}
/**
* Get insurance
*
* #return string
*/
public function getInsurance()
{
return $this->insurance;
}
/**
* Set incrementUnit
*
* #param string $incrementUnit
* #return PostalCharge
*/
public function setIncrementUnit($incrementUnit)
{
$this->incrementUnit = $incrementUnit;
return $this;
}
/**
* Get incrementUnit
*
* #return string
*/
public function getIncrementUnit()
{
return $this->incrementUnit;
}
/**
* Set currencyCode
*
* #param string $currencyCode
* #return PostalCharge
*/
public function setCurrencyCode($currencyCode)
{
$this->currencyCode = $currencyCode;
return $this;
}
/**
* Get currencyCode
*
* #return string
*/
public function getCurrencyCode()
{
return $this->currencyCode;
}
/**
* Set countryCode
*
* #param string $countryCode
* #return PostalCharge
*/
public function setCountryCode($countryCode)
{
$this->countryCode = $countryCode;
return $this;
}
/**
* Get countryCode
*
* #return string
*/
public function getCountryCode()
{
return $this->countryCode;
}
/**
* Set deliveryCompany
*
* #param \Sokosimu\PostalDeliveryBundle\Entity\DeliveryCompany $deliveryCompany
* #return PostalCharge
*/
public function setDeliveryCompany(\Sokosimu\PostalDeliveryBundle\Entity\DeliveryCompany $deliveryCompany = null)
{
$this->deliveryCompany = $deliveryCompany;
return $this;
}
/**
* Get deliveryCompany
*
* #return \Sokosimu\PostalDeliveryBundle\Entity\DeliveryCompany
*/
public function getDeliveryCompany()
{
return $this->deliveryCompany;
}
}
As I understand, you wan to remove every postalCharge from your delivery company. You seems to lack basic knowledge of doctrine object representation, I would recommend you to read and understand the documentation (specially the oneToMany section): http://symfony.com/doc/current/doctrine.html
However this is how you should do it:
public function clearRatesAction(DeliveryCompany $deliveryCompany){
$em = $this->get('doctrine')->getManager();
$em->getConnection()->beginTransaction();
try {
foreach($deliveryCompany->getRates() as $postalCharge) {
$em->remove($postalCharge);
}
$em->flush( );
$em->getConnection()->commit();
} catch(Exception $e){
$em->getConnection()->rollback();
throw $e;
}
Exception shown:
"No mapping file found named '/Users/josedelrio/AimerAgronomia/src/Aimer/PlataformaBundle/Resources/config/doctrine/ExplotacionRepository.orm.yml' for class 'Aimer\PlataformaBundle\Entity\ExplotacionRepository".
It happens when I try to call for the Repository method. I don't understand why is asking for that file.
Entity code:
#src/AimerPlataformaBundle/Resources/config/doctrine/Explotacion.orm.yml
Aimer\PlataformaBundle\Entity\Explotacion:
type: entity
table: Explotacion
repositoryClass: Aimer\PlataformaBundle\Entity\ExplotacionRepository
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
nombre:
type: string
length: 100
kgCuota:
type: float
manyToOne:
idParroquia:
targetEntity: Parroquia
joinColumn:
name: idParroquia
referencedColumnName: id
nullable: false
unique: FALSE
Code generated with doctrine:generate:entities
Explotacion.php
<?php
namespace Aimer\PlataformaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Explotacion
*/
class Explotacion
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $nombre;
/**
* #var integer
*/
private $idTecnico;
/**
* #var integer
*/
private $idServizo;
/**
* #var string
*/
private $nif;
/**
* #var string
*/
private $cea;
/**
* #var string
*/
private $lugar;
/**
* #var float
*/
private $sau;
/**
* #var integer
*/
private $numCabezas;
/**
* #var float
*/
private $haMillo;
/**
* #var float
*/
private $haHerba;
/**
* #var float
*/
private $kgCuota;
/**
* #var \Aimer\PlataformaBundle\Entity\Parroquia
*/
private $idParroquia;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* #param string $nombre
* #return Explotacion
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set idTecnico
*
* #param integer $idTecnico
* #return Explotacion
*/
public function setIdTecnico($idTecnico)
{
$this->idTecnico = $idTecnico;
return $this;
}
/**
* Get idTecnico
*
* #return integer
*/
public function getIdTecnico()
{
return $this->idTecnico;
}
/**
* Set idServizo
*
* #param integer $idServizo
* #return Explotacion
*/
public function setIdServizo($idServizo)
{
$this->idServizo = $idServizo;
return $this;
}
/**
* Get idServizo
*
* #return integer
*/
public function getIdServizo()
{
return $this->idServizo;
}
/**
* Set nif
*
* #param string $nif
* #return Explotacion
*/
public function setNif($nif)
{
$this->nif = $nif;
return $this;
}
/**
* Get nif
*
* #return string
*/
public function getNif()
{
return $this->nif;
}
/**
* Set cea
*
* #param string $cea
* #return Explotacion
*/
public function setCea($cea)
{
$this->cea = $cea;
return $this;
}
/**
* Get cea
*
* #return string
*/
public function getCea()
{
return $this->cea;
}
/**
* Set lugar
*
* #param string $lugar
* #return Explotacion
*/
public function setLugar($lugar)
{
$this->lugar = $lugar;
return $this;
}
/**
* Get lugar
*
* #return string
*/
public function getLugar()
{
return $this->lugar;
}
/**
* Set sau
*
* #param float $sau
* #return Explotacion
*/
public function setSau($sau)
{
$this->sau = $sau;
return $this;
}
/**
* Get sau
*
* #return float
*/
public function getSau()
{
return $this->sau;
}
/**
* Set numCabezas
*
* #param integer $numCabezas
* #return Explotacion
*/
public function setNumCabezas($numCabezas)
{
$this->numCabezas = $numCabezas;
return $this;
}
/**
* Get numCabezas
*
* #return integer
*/
public function getNumCabezas()
{
return $this->numCabezas;
}
/**
* Set haMillo
*
* #param float $haMillo
* #return Explotacion
*/
public function setHaMillo($haMillo)
{
$this->haMillo = $haMillo;
return $this;
}
/**
* Get haMillo
*
* #return float
*/
public function getHaMillo()
{
return $this->haMillo;
}
/**
* Set haHerba
*
* #param float $haHerba
* #return Explotacion
*/
public function setHaHerba($haHerba)
{
$this->haHerba = $haHerba;
return $this;
}
/**
* Get haHerba
*
* #return float
*/
public function getHaHerba()
{
return $this->haHerba;
}
/**
* Set kgCuota
*
* #param float $kgCuota
* #return Explotacion
*/
public function setKgCuota($kgCuota)
{
$this->kgCuota = $kgCuota;
return $this;
}
/**
* Get kgCuota
*
* #return float
*/
public function getKgCuota()
{
return $this->kgCuota;
}
/**
* Set idParroquia
*
* #param \Aimer\PlataformaBundle\Entity\Parroquia $idParroquia
* #return Explotacion
*/
public function setIdParroquia(\Aimer\PlataformaBundle\Entity\Parroquia $idParroquia)
{
$this->idParroquia = $idParroquia;
return $this;
}
/**
* Get idParroquia
*
* #return \Aimer\PlataformaBundle\Entity\Parroquia
*/
public function getIdParroquia()
{
return $this->idParroquia;
}
}
And the repository file
<?php
namespace Aimer\PlataformaBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ExplotacionRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ExplotacionRepository extends EntityRepository
{
public function nomeConcello()
{
/*
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT c.nombre FROM Concello c WHERE c.id = (SELECT idConcello FROM Parroquia WHERE id = :id)'
)->setParameter('id', 1);
$concello = $query->getResult();
return $concello;
*/
$this->getEntityManager()
->createQuery('SELECT c.nombre FROM Concello c WHERE c.id = (SELECT idConcello FROM Parroquia WHERE id = :id)')
->setParameter('id', 1)
->getResult();
}
}
Here is the code where I try to use the Repository method, inside ExplotacionController file:
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AimerPlataformaBundle:Explotacion')->find($id);
$nomeConcello = $em->getRepository('AimerPlataformaBundle:ExplotacionRepository')->nomeConcello();
if (!$entity) {
throw $this->createNotFoundException('Unable to find Explotacion entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('AimerPlataformaBundle:Explotacion:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
'nomeConcello' => $nomeConcello, ));
}
You can invoke the repository class by calling the entity.
like this
$nomeConcello = $em->getRepository('AimerPlataformaBundle:Explotacion')->nomeConcello();
No need of explicit calling.
Please see the document