I'm trying to get a multilingual site up with A2lix-i18 & a2lix-form, but I've seem to hit a bump.
I'm able to persist the records, but the translatable_id never gets set.
Any ideas on how this could be occuring?
<?php
//Message.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="messages")
*/
class Message
{
use \A2lix\I18nDoctrineBundle\Doctrine\ORM\Util\Translatable;
/**
* #ORM\Column(type="guid")
* #ORM\Id
* #ORM\GeneratedValue(strategy="UUID")
*/
protected $id;
/**
* #ORM\Column(type="datetime")
*/
protected $created;
/**
* #ORM\OneToOne(targetEntity="User")
* #ORM\JoinColumn(name="author_id", referencedColumnName="id")
*/
protected $author;
/**
*/
protected $translations;
public function getTranslations(){
return $this->translations;
}
public function addTranslation($translation){
$this->translations[] = $translation;
}
public function __construct(){
$this->created = new \DateTime();
$this->translations = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return guid
*/
public function getId()
{
return $this->id;
}
public function getCreated()
{
return $this->created;
}
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Set author
*
* #param \AppBundle\Entity\User $author
* #return Message
*/
public function setAuthor(\AppBundle\Entity\User $author = null)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return \AppBundle\Entity\User
*/
public function getAuthor()
{
return $this->author;
}
public function setTranslatable($translatable)
{
$this->translatable = $translatable;
}
}
-
//MessageTranslation.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class MessageTranslation implements \A2lix\I18nDoctrineBundle\Doctrine\Interfaces\ManyLocalesInterface
{
use \A2lix\I18nDoctrineBundle\Doctrine\ORM\Util\Translation;
/**
* #ORM\Column(type="text")
*/
protected $message;
/**
* Set message
*
* #param string $message
* #return MessageTranslation
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
/**
* Get message
*
* #return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function setId($id){
$this->id = $id;
}
/**
* Set locale
*
* #param string $locale
* #return MessageTranslation
*/
public function setLocales($locales)
{
$this->locales = $locales;
return $this;
}
/**
* Get locale
*
* #return string
*/
public function getLocales()
{
return $this->locales;
}
public function setTranslatable($translatable)
{
$this->translatable = $translatable;
}
public function getTranslatable()
{
return $this->translatable;
}
}
I was overriding the default addTranslation and removeTranslation functions. Solved now
Related
During a production cache clear I have this message : The type hint of parameter "imageFile" in method "setImageFile" in class "App\Entity\Evenement" is invalid. I follow the instruction of the VichUploaderBundle's documentation on github "basic usage".
Thanks for your help !
below the code of the entity :
<?php
namespace App\Entity;
use App\Repository\EvenementRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\component\HttpFoundation\File\File;
use Symfony\component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity(repositoryClass=EvenementRepository::class)
* #vich\Uploadable
*/
class Evenement
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*
*/
private $titre;
/**
* #ORM\Column(type="string", length=2000, nullable=true)
*/
private $description;
/**
* #ORM\Column(type="string", length=500, nullable=true)
* #Assert\Url()
*/
private $visuel;
/**
* #Vich\UploadableField(mapping="evenement", fileNameProperty="imageName")
* #var File|null
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #var string|null
*/
private $imageName;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTimeInterface|null
*/
private $updatedAt;
/**
* #ORM\Column(type="string", length=500, nullable=true)
*/
private $tarifs;
/**
* #ORM\Column(type="datetime")
*/
private $date;
/**
* #ORM\ManyToMany(targetEntity=Film::class, inversedBy="evenements")
*/
private $films;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateFin;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $video;
public function __construct()
{
$this->films = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitre(): ?string
{
return $this->titre;
}
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getVisuel(): ?string
{
return $this->visuel;
}
public function setVisuel(?string $visuel): self
{
$this->visuel = $visuel;
return $this;
}
public function getTarifs(): ?string
{
return $this->tarifs;
}
public function setTarifs(?string $tarifs): self
{
$this->tarifs = $tarifs;
return $this;
}
public function getDate(): ?\DateTimeInterface
{
return $this->date;
}
public function setDate(\DateTimeInterface $date): self
{
$this->date = $date;
return $this;
}
/**
* #return Collection|Film[]
*/
public function getFilms(): Collection
{
return $this->films;
}
public function addFilm(Film $film): self
{
if (!$this->films->contains($film)) {
$this->films[] = $film;
}
return $this;
}
public function removeFilm(Film $film): self
{
$this->films->removeElement($film);
return $this;
}
public function getDateFin(): ?\DateTimeInterface
{
return $this->dateFin;
}
public function setDateFin(?\DateTimeInterface $dateFin): self
{
$this->dateFin = $dateFin;
return $this;
}
public function getVideo(): ?string
{
return $this->video;
}
public function setVideo(?string $video): self
{
$this->video = $video;
return $this;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $imageFile
*/
public function setImageFile(?File $imageFile = null): void
{
$this->imageFile = $imageFile;
if (null !== $imageFile) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
}
public function getImageFile(): ?File
{
return $this->imageFile;
}
public function setImageName(?string $imageName): void
{
$this->imageName = $imageName;
}
public function getImageName(): ?string
{
return $this->imageName;
}
}
Please set your fields according to this
Note: Don't forgot to update your database
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Entity\File as EmbeddedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Assert\File(
* maxSize="51200k",
* mimeTypes = {
* "image/jpeg",
* "image/gif",
* "image/png",
* }
* )
* #Vich\UploadableField(
* mapping="evenement_image",
* fileNameProperty="imageFile.name",
* size="imageFile.size",
* originalName="imageFile.originalName",
* mimeType="imageFile.mimeType"
* )
*
* #var File|null
*/
protected $image;
/**
* #ORM\Embedded(class="Vich\UploaderBundle\Entity\File")
*
* #var EmbeddedFile
*/
protected $imageFile;
public function __construct()
{
$this->imageFile = new EmbeddedFile();
}
public function setImage(?File $image = null): void
{
$this->image = $image;
if (null !== $image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new DateTimeImmutable();
}
}
public function getImage(): ?File
{
return $this->image;
}
public function getImageFile(): ?EmbeddedFile
{
return $this->imageFile;
}
public function setImageFile(EmbeddedFile $imageFile): self
{
$this->imageFile = $imageFile;
return $this;
}
Impossible to create a new event, I always get 415 error
I test with postman, if I test the same endpoint with ParamConverter annotation, I can reach the function.
So the error should come from configuration
Here is my controller
<?php
namespace App\Controller;
use App\Entity\Event;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\Validator\ConstraintViolationListInterface;
/**
* Event controller.
* #Route("/api", name="api_")
*/
class EventController extends AbstractFOSRestController
{
/**
* Create New Event
* #Rest\Post("/event/create")
* #param Event $event
* #param ConstraintViolationListInterface $violations
* #ParamConverter("event", converter="fos_rest.request_body")
* #throws
* #return View
*/
public function createAction(Event $event, ConstraintViolationListInterface $violations)
{
if (count($violations)) {
return View::create($violations, Response::HTTP_BAD_REQUEST);
}
$em = $this->getDoctrine()->getManager();
$em->persist($event);
$em->flush();
return View::create($event, Response::HTTP_OK);
}
}
This is Fost Rest configuration, I checked the documentation and it should be ok
# Read the documentation: https://symfony.com/doc/master/bundles/FOSRestBundle/index.html
fos_rest:
routing_loader:
default_format: json
include_format: false
body_listener: true
format_listener:
rules:
- { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
param_fetcher_listener: true
access_denied_listener:
json: true
view:
view_response_listener: 'force'
formats:
json: true
body_converter:
enabled: true
validate: true
validation_errors_argument: violations
And to finish, event entity
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="event")
*/
class Event
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User")
*
*/
protected $organizer;
/**
* #ORM\Column(type="text")
* #Assert\NotBlank
*/
protected $title;
/**
* #ORM\Column(type="text")
*/
protected $description;
/**
* #ORM\Column(type="text")
*/
protected $address;
/**
* #ORM\Column(type="text")
*/
protected $city;
/**
* #ORM\Column(type="text")
*/
protected $postCode;
/**
* #ORM\Column(type="text")
*/
protected $coverPicture;
/**
* #ORM\Column(type="float")
*/
protected $price;
/**
* #ORM\Column(type="integer")
*/
protected $maxAttendees;
/**
* #ORM\Column(type="datetime")
*/
protected $dateFrom;
/**
* #ORM\Column(type="datetime")
*/
protected $dateTo;
/**
* #ORM\Column(type="integer")
*/
protected $status;
/**
* #ORM\Column(type="boolean")
*/
protected $featured;
/**
* List of attendees
* #ORM\ManyToMany(targetEntity="User")
* #ORM\JoinTable(name="event_atendees",
* joinColumns={#ORM\JoinColumn(name="event_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="attendee_id", referencedColumnName="id")}
* )
*/
protected $attendees;
public function __construct()
{
$this->attendees = new ArrayCollection();
}
/**
* #return int
*/
public function getId() : int
{
return $this->id;
}
/**
* #param int $id
* #return Event
*/
public function setId(int $id)
{
$this->id = $id;
return $this;
}
/**
* #return User
*/
public function getOrganizer() : User
{
return $this->organizer;
}
/**
* #param User $organizer
* #return Event
*/
public function setOrganizer(User $organizer)
{
$this->organizer = $organizer;
return $this;
}
/**
* #return string
*/
public function getTitle() : string
{
return $this->title;
}
/**
* #param string $title
* #return Event
*/
public function setTitle(string $title)
{
$this->title = $title;
return $this;
}
/**
* #return string
*/
public function getDescription() : string
{
return $this->description;
}
/**
* #param string $description
* #return Event
*/
public function setDescription(string $description)
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getAddress() : string
{
return $this->address;
}
/**
* #param string $address
* #return Event
*/
public function setAddress(string $address)
{
$this->address = $address;
return $this;
}
/**
* #return string
*/
public function getCity() : string
{
return $this->city;
}
/**
* #param string $city
* #return Event
*/
public function setCity(string $city)
{
$this->city = $city;
return $this;
}
/**
* #return string
*/
public function getPostCode() : string
{
return $this->postCode;
}
/**
* #param string $postCode
* #return Event
*/
public function setPostCode(string $postCode)
{
$this->postCode = $postCode;
return $this;
}
/**
* #return string
*/
public function getCoverPicture() : string
{
return $this->coverPicture;
}
/**
* #param string $coverPicture
* #return Event
*/
public function setCoverPicture(string $coverPicture)
{
$this->coverPicture = $coverPicture;
return $this;
}
/**
* #return float
*/
public function getPrice() : float
{
return $this->price;
}
/**
* #param float $price
* #return Event
*/
public function setPrice(float $price)
{
$this->price = $price;
return $this;
}
/**
* #return int
*/
public function getMaxAttendees() : int
{
return $this->maxAttendees;
}
/**
* #param int $maxAttendees
* #return Event
*/
public function setMaxAttendees(int $maxAttendees)
{
$this->maxAttendees = $maxAttendees;
return $this;
}
/**
* #return DateTime
*/
public function getDateFrom() : DateTime
{
return $this->dateFrom;
}
/**
* #param DateTime $dateFrom
* #return Event
*/
public function setDateFrom(DateTime $dateFrom)
{
$this->dateFrom = $dateFrom;
return $this;
}
/**
* #return DateTime
*/
public function getDateTo() : DateTime
{
return $this->dateTo;
}
/**
* #param DateTime $dateTo
* #return Event
*/
public function setDateTo(DateTime $dateTo)
{
$this->dateTo = $dateTo;
return $this;
}
/**
* #return int
*/
public function getStatus() : int
{
return $this->status;
}
/**
* #param int $status
* #return Event
*/
public function setStatus(int $status)
{
$this->status = $status;
return $this;
}
/**
* #return bool
*/
public function getFeatured() : bool
{
return $this->featured;
}
/**
* #param bool $featured
* #return Event
*/
public function setFeatured(bool $featured)
{
$this->featured = $featured;
return $this;
}
/**
* #return User[]
*/
public function getAttendees() : ArrayCollection
{
return $this->attendees;
}
/**
* #param User[] $attendees
* #return Event
*/
public function setAttendees($attendees)
{
$this->attendees = $attendees;
return $this;
}
/**
* #param User $attendee
*/
public function addAttendee(User $attendee) {
$this->attendees->add($attendee);
}
/**
* #param User $attendee
*/
public function removeAttendee(User $attendee) {
$this->attendees->removeElement($attendee);
}
}
Is somebody have an idea ?
I trying make relation in symphony through this http://symfony.com/doc/current/doctrine/associations.html
problemm is that when i get post and wont get related entitie (rss) i get null
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Post
* #ORM\Entity
* #ORM\Table(name="post")
*/
class Post
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $title;
/**
* #var string
*/
private $text;
/**
* #ORM\ManyToOne(targetEntity="Rss", inversedBy="posts")
* #ORM\JoinColumn(name="link", referencedColumnName="id")
*/
private $rss;
/**
* #var \DateTime
*/
private $createdAt;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set text
*
* #param string $text
*
* #return Post
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set link
*
* #param string $link
*
* #return Post
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Post
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #var integer
*/
private $user_id;
/**
* Set userId
*
* #param integer $userId
*
* #return Post
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->user_id;
}
/**
* #var integer
*/
private $link;
public function setRss($rss){
$this->rss = $rss;
}
public function getRss(){
return $this->rss;
}
}
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* rss
*
* #ORM\Entity
* #ORM\Table(name="rss")
*/
class Rss
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #var string
*/
private $address;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return rss
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set address
*
* #param string $address
*
* #return rss
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* #var \DateTime
*/
private $lastUpdate;
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="Rss")
*/
private $posts;
public function __construct()
{
$this->posts = new ArrayCollection();
}
public function getPosts(){
return $this->posts;
}
public function setPosts($posts){
$this->posts[] = $posts;
}
/**
* Set lastUpdate
*
* #param \DateTime $lastUpdate
*
* #return rss
*/
public function setLastUpdate($lastUpdate)
{
$this->lastUpdate = $lastUpdate;
return $this;
}
/**
* Get lastUpdate
*
* #return \DateTime
*/
public function getLastUpdate()
{
return $this->lastUpdate;
}
/**
* #var string
*/
private $pageaddress;
/**
* Set pageaddress
*
* #param string $pageaddress
*
* #return rss
*/
public function setPageaddress($pageaddress)
{
$this->pageaddress = $pageaddress;
return $this;
}
/**
* Get pageaddress
*
* #return string
*/
public function getPageaddress()
{
return $this->pageaddress;
}
}
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository('AppBundle:Post')->findAll();
$post = $this->getDoctrine()
->getRepository('AppBundle:Post')
->find(1);
$post->getRss();
This can help you:
https://knpuniversity.com/screencast/doctrine-relations/many-to-one-relation
also you can try modifying the variable $id
private $id
for
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
To create a primary key.
Entity
class Post
/**
* #ORM\ManyToOne(targetEntity="Rss", inversedBy="post")
* #ORM\JoinColumn(nullable=false)
*/
private $rss;
class Rss
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="rss")
* #ORM\OrderBy({"createdAt"="DESC"})
*/
private $post;
and the class Post you will need to create a constructor like this
public function __construct()
{
$this->posts = new ArrayCollection();
}
/**
* #return ArrayCollection|GenusNote[]
*/
public function getPosts()
{
return $this->notes;
}
I hope it can help you
I have two Entities
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;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="first_name", type="text", nullable=true)
*/
protected $firstName;
/**
* #ORM\Column(name="last_name", type="text", nullable=true)
*/
protected $lastName;
/**
* #ORM\Column(type="bigint", nullable=true)
*/
protected $phone;
/**
* #ORM\Column(name="birth_date", type="date", nullable=true)
*/
protected $birthDate;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $gender;
/**
* #ORM\Column(name="location_country", type="text", nullable=true)
*/
protected $locationCountry;
/**
* #ORM\Column(name="location_city", type="text", nullable=true)
*/
protected $locationCity;
/**
* #ORM\Column( type="text", nullable=true)
*/
protected $avatar;
/**
* #ORM\Column(name="wall_image", type="text", nullable=true)
*/
protected $wallImage;
/**
* #ORM\Column( type="text", nullable=true)
*/
protected $about;
/**
* #ORM\OneToMany(targetEntity="Follower", mappedBy="user")
*/
protected $followers;
/**
* #ORM\OneToMany(targetEntity="Follower", mappedBy="follower")
*/
protected $followings;
/**
* Is followed. Used when checking is followed by another user.
*/
protected $isFollowed = false;
/**
* #ORM\OneToMany(targetEntity="Photo", mappedBy="user")
* #ORM\OrderBy({"id" = "DESC"})
*/
protected $photos;
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
public function getPhone()
{
return $this->phone;
}
public function getBirthDate()
{
return $this->birthDate;
}
public function getGender()
{
return $this->gender;
}
public function getLocationCountry()
{
return $this->locationCountry;
}
public function getLocationCity()
{
return $this->locationCity;
}
public function getAvatar()
{
return $this->avatar;
}
public function getAvatarImage()
{
return $this->getAvatarPath().$this->avatar;
}
public function getWallImage()
{
return $this->wallImage;
}
public function getAbout()
{
return $this->about;
}
public function getAvatarPath()
{
return '/web/uploads/avatars/'.$this->id.'/';
}
public function getWallImagePath()
{
return '/web/uploads/wall/'.$this->id.'/';
}
public function getFollowers()
{
return $this->followers;
}
public function getFollowings()
{
return $this->followings;
}
public function getFollowersCount()
{
//print_r($this->followers->toArray());
}
public function getPhotos()
{
return $this->photos;
}
public function isFollowed()
{
return $this->isFollowed;
}
public function setFirstName($value)
{
$this->firstName = $value;
}
public function setLastName($value)
{
$this->lastName = $value;
}
public function setPhone($value)
{
$this->phone = $value;
}
public function setBirthDate($value)
{
$this->birthDate = $value;
}
public function setGender($value)
{
$this->gender = $value;
}
public function setLocationCountry($value)
{
$this->locationCountry = $value;
}
public function setLocationCity($value)
{
$this->locationCity = $value;
}
public function setAvatar($path)
{
$this->avatar = $path;
}
public function setWallImage($path)
{
$this->wallImage = $path;
}
public function setAbout($about)
{
$this->about = $about;
}
public function setFollowed($isFollowed)
{
$this->isFollowed = $isFollowed;
}
}
Photo
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="photos")
*/
class Photo
{
const
CATEGORY_PHOTOGRAPHY = 1,
CATEGORY_PAINTING = 2,
CATEGORY_3D = 3;
/*
* Flow photos limit
*/
const FLOW_PHOTOS_LIMIT = 15;
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="photos")
*/
protected $user;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $title;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $description;
/**
* #ORM\Column(type="text")
*/
protected $name;
/**
* #ORM\ManyToOne(targetEntity="PhotoCategory")
*/
protected $category;
/**
* #ORM\Column(name="creation_date", type="datetime")
*/
protected $creationDate;
/**
* #ORM\Column(name="edit_date", type="datetime", nullable=true)
*/
protected $editDate;
/**
* #ORM\Column(name="is_moderated", type="boolean")
*/
protected $isModerated = false;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
protected $isActive = true;
/**
* #ORM\OneToMany(targetEntity="Comment", mappedBy="photo")
* #ORM\OrderBy({"id" = "DESC"})
*/
protected $comments;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set user
*
* #param User $user
*
* #return Photo
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return User $user
*/
public function getUser()
{
return $this->user;
}
/**
* Get category
*
* #return Category $category
*/
public function getCategory()
{
return $this->category;
}
/**
* Set title
*
* #param string $title
*
* #return Photo
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Get creationDate
*
* #return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* Get editDate
*
* #return \DateTime
*/
public function getEditDate()
{
return $this->editDate;
}
/**
* Get is active
*
* #return integer
*/
public function isActive()
{
return $this->isActive;
}
/**
* Get is moderated
*
* #return integer
*/
public function isModerated()
{
return $this->isModerated;
}
/*
* Get image
*
* #return string
*/
public function getImage()
{
return $this->getWebDirectory().$this->getName();
}
/*
* Get image directory
*
* #return string
*/
public function getDirectory()
{
return __DIR__.'/../../../web/uploads/photos/'.$this->getUser()->getId().'/'.$this->creationDate->format('Y-m-d').'/';
}
/*
* Get image web directory
*
* #return string
*/
public function getWebDirectory()
{
return '/web/uploads/photos/'.$this->getUser()->getId().'/'.$this->creationDate->format('Y-m-d').'/';
}
/*
* Get comments
*/
public function getComments()
{
return $this->comments;
}
/**
* Set description
*
* #param string $description
*
* #return Photo
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set name
*
* #param string $name
*
* #return Photo
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set creationDate
*
* #param \DateTime $creationDate
*/
public function setCreationDate(\DateTime $creationDate)
{
$this->creationDate = $creationDate;
}
/**
* Set editDate
*
* #param \DateTime $editDate
*/
public function setEditDate(\DateTime $editDate)
{
$this->editDate = $editDate;
}
/**
* Set active
*/
public function setActive($active)
{
$this->isActive = $active;
}
/**
* Set category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* Set moderated
*/
public function setModerated($moderated)
{
$this->isModerated = $moderated;
}
}
As you see, i have isActive in Photo, which is telling is photo deleted or not. So, i get all users photos via User->getPhotos() which is one-to-many. But it return all users photos. How should be done, so it returns all photos which have isActive = true?
thank you
you can try the filter method to query inside entities
$user->getPhotos()->filter(
function($photo) {
return $photo->isActive();
}
);
There are a number of ways you can do this.
Cosmin provided one for you, which will result in Doctrine loading each photo, and then PHP code checking to see whether or not it is active. This will work in the most number of situations, but will potentially be slow inefficient.
Yet another solution, is to use "criteria":
$exp = new \Doctrine\ORM\Query\Expr();
$activePhotos = $user->getPhotos()->matching(
new \Doctrine\Common\Collections\Criteria(
$exp->eq('active', true)
)
);
This will do something similar to the filter that Cosmin suggested, but allow for Doctrine to filter at the database level.
You can create a method inside the User entity, using the code of #Cosmin Ordean :) Something like this
public function getActivePhotos() {
return $this->getPhotos()->filter(
function($photo) {
return $photo->isActive();
}
);
}
I want to update some rows from table comments.
class TryCommentsCommand extends ContainerAwareCommand
{
protected function configure()
{
//blah-blah-blah
}
private function update_comments($step_size, OutputInterface $output)
{
$doctrine = $this->getContainer()->get('doctrine');
$not_moderated_comments = $doctrine->getRepository('***Bundle:Comments')
->findBy(array('is_automoderated' => false))
->orderBy('c.date', 'DESC')
->setMaxResults($step_size)
->setFirstResult(0)
->getQuery()->getResult();
for ($not_moderated_comments as $comment)
{
$comment.setIsAutomoderated(true);
$comment.save();
}
}
protected function execute(InputInterface $input, OutputInterface $output)
{
self::update_comments(intval($input->getArgument('step')), $output);
}
}
I'd write this command and try to run this, but got the error
Fatal error: Class 'Blogger\BlogBundle\Repository\BlogRepository' not found in C:\Users\.. ..\vendor\doctrine\orm\lib\Doctrine\ORM\Repository\DefaultRepositoryFactory.php on line 75
How to fix it? How get entities from table?
UPD: My ***Bundle:Comments
namespace pv\***Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Comments
*/
class Comments
{
/**
* #var integer
*/
private $id;
/**
* #var \DateTime
*/
private $date;
/**
* #var string
*/
private $name;
/**
* #var string
*/
private $comment;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set date
*
* #param \DateTime $date
* #return Comments
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set name
*
* #param string $name
* #return Comments
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set name
*
* #param string $name
* #return Comments
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Set comment
*
* #param string $comment
* #return Comments
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* #return string
*/
public function getComment()
{
return $this->comment;
}
}