I try to filter my elastica query by language. My query works fine, but when i add the filter, i get 0 result.
My entity :
<?php
namespace Youmiam\RecipeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* Product
*
* #ORM\Table(name="product")
* #ExclusionPolicy("all")
* #ORM\Entity(repositoryClass="Youmiam\RecipeBundle\Entity\ProductRepository")
*/
class Product
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="Youmiam\RecipeBundle\Entity\Brand", inversedBy="products")
* #ORM\JoinColumn(name="brand_id", referencedColumnName="id")
*/
private $brand;
/**
* #ORM\ManyToOne(targetEntity="Youmiam\RecipeBundle\Entity\Ingredient", inversedBy="products")
* #ORM\JoinColumn(name="ingredient_id", referencedColumnName="id")
* #Expose
*/
private $ingredient;
/**
* #ORM\ManyToMany(targetEntity="Youmiam\RecipeBundle\Entity\Recipe", inversedBy="products")
* #ORM\JoinTable(name="products__recipes")
*/
private $recipes;
/**
* #ORM\OneToMany(targetEntity="Youmiam\RecipeBundle\Entity\Quantity", mappedBy="product", orphanRemoval=true, cascade={"all"})
*/
private $quantities;
/**
* #var \stdClass
*
* #ORM\Column(name="photo", type="string", length=255, nullable=true)
* #Expose
*/
private $photo;
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Product
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set name
*
* #param string $name
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set ingredient
*
* #param \Youmiam\RecipeBundle\Entity\Ingredient $ingredient
* #return Product
*/
public function setIngredient(\Youmiam\RecipeBundle\Entity\Ingredient $ingredient = null)
{
$this->ingredient = $ingredient;
return $this;
}
/**
* Get ingredient
*
* #return \Youmiam\RecipeBundle\Entity\Ingredient
*/
public function getIngredient()
{
return $this->ingredient;
}
/**
* Set brand
*
* #param \Youmiam\RecipeBundle\Entity\Brand $brand
* #return Product
*/
public function setBrand(\Youmiam\RecipeBundle\Entity\Brand $brand = null)
{
$this->brand = $brand;
return $this;
}
/**
* Get brand
*
* #return \Youmiam\RecipeBundle\Entity\Brand
*/
public function getBrand()
{
return $this->brand;
}
/**
* Constructor
*/
public function __construct()
{
$this->recipes = new \Doctrine\Common\Collections\ArrayCollection();
$this->quantities = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set photo
*
* #param string $photo
* #return Product
*/
public function setPhoto($photo)
{
$this->photo = $photo;
return $this;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto()
{
return $this->photo;
}
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* Add recipes
*
* #param \Youmiam\RecipeBundle\Entity\Recipe $recipes
* #return Product
*/
public function addRecipe(\Youmiam\RecipeBundle\Entity\Recipe $recipes)
{
$this->recipes[] = $recipes;
return $this;
}
/**
* Remove recipes
*
* #param \Youmiam\RecipeBundle\Entity\Recipe $recipes
*/
public function removeRecipe(\Youmiam\RecipeBundle\Entity\Recipe $recipes)
{
$this->recipes->removeElement($recipes);
}
/**
* Get recipes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getRecipes()
{
return $this->recipes;
}
/**
* Add quantities
*
* #param \Youmiam\RecipeBundle\Entity\Quantity $quantities
* #return Product
*/
public function addQuantity(\Youmiam\RecipeBundle\Entity\Quantity $quantities)
{
$this->quantities[] = $quantities;
return $this;
}
/**
* Remove quantities
*
* #param \Youmiam\RecipeBundle\Entity\Quantity $quantities
*/
public function removeQuantity(\Youmiam\RecipeBundle\Entity\Quantity $quantities)
{
$this->quantities->removeElement($quantities);
}
/**
* Get quantities
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getQuantities()
{
return $this->quantities;
}
/**
* get the class Name
* #return string $className
*/
public function getClass()
{
return "Product";
}
/**
* #return Language
*/
public function getBrandLanguage()
{
return $this->brand->getLanguage();
}
}
My Config.yml
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
indexes:
youmiam:
settings:
index:
analysis:
analyzer:
keyword_analyser:
type: custom
tokenizer: keyword
classic_analyser:
type: custom
tokenizer: lowercase
filter : [my_snow,asciifolding]
ingr_analyser:
type: custom
tokenizer: lowercase
filter : [my_ing_ngram,asciifolding]
recipe_analyser:
type: custom
tokenizer: lowercase
filter : [my_recipe_ngram,asciifolding]
testfollower:
type: stop
stopwords : [',']
filter:
my_snow:
type : "snowball"
language : "French"
my_ing_ngram:
type: "nGram"
min_gram: 3
max_gram: 8
my_recipe_ngram:
type: "nGram"
min_gram: 4
max_gram: 10
char_filter:
my_whtoa :
type : mapping
mappings : ["' '=>a",]
client: default
finder: ~
types:
product:
mappings:
name: { boost: 10, analyzer: classic_analyser }
brand: { boost: 10, analyzer: classic_analyser }
ingredient: { boost: 10, analyzer: classic_analyser }
brandLanguage: { boost: 10 }
persistence:
driver: orm
model: Youmiam\RecipeBundle\Entity\Product
provider: ~
listener: ~
finder: ~
repository: Youmiam\RecipeBundle\SearchRepository\ProductRepository
And then, in my fos elastica repository, i have this code :
$boolQuery = new \Elastica\Query\Bool();
$query = new \Elastica\Query;
$queryString = new \Elastica\Query\QueryString();
$queryString->setQuery($searchText);
$queryString->setAnalyzer('classic_analyser');
$queryString->setFields(array('product.name', 'product.brand', 'product.ingredient'));
$boolQuery->addMust($queryString);
$query->setQuery($boolQuery);
$filter = new \Elastica\Filter\Term();
$filter->setTerm('brandLanguage', 'fr');
$query->setPostFilter($filter);
return $this->find($query);
I tried to put my query directly in a controller, but same result. I really don't know why my filter return no result.
Hope someone could help, cause i'm really don't see the answer
First thing to do is testing your query outside Elastica, you can get the JSON from the Sf2 Profiler or from the logs.
Next, make sure your documents are sent in Elasticsearch the way you want (perform a simple GET /youmiam/product/_search request to see them, in a tool like Sense).
I see that your brandLanguage field is using the standard analyzer, you can see how Elasticsearch index it with a query like this: GET /youmiam/_analyze?field=brandLanguage&text=FR - is there a token with the exact value fr? If not, there will be no match.
Best practice is to set this kind of field as "not_analyzed" too.
Beside that there is no issue with your code (you could use a FilteredQuery instead of postFilter but that's not the issue), you should look more closely at what is indexed and how to query it directly via Sense, and then translate it with Elastica.
Related
First, I'm a french beginner in Symfony4,
Second, I already searched in Symfony Documentation, asked some friends, called my mom..
I'm working on EasyAdminBundle on the form Edit / New Entity.
I have to change the label of my entities but when I do it, my form type is changing.
Here's when picture of my view before editing:
I want to change ' id_equipe' to 'Domicile (home for english )' and id_equipe_equipes to 'exterieur (Visitors)'
So when I tried this :
fields:
- { property: 'id_equipe', label: equipe_domicile}
- { property: 'id_equipe_equipes', label: equipe_extérieur}
The type of the properties is changing to TextArea and I don't know why.
I tried to put a new type like this :
- { property: 'id_equipe', label: equipe_domicile, type: 'choice'}
but my select is blank, I cannot choose anything.
This is what I get:
Thanks you guys
Ps: sorry for ten years old english
So, look, if I understand correctly - id_equipe is a key to external entity. So, this way, to get it worked - you need to use type: 'entity' and also add type_options option, something like that:
- { property: 'id_equipe', label: 'Domicile', type: 'entity', type_options: { class: 'App\Entity\Equipe', multiple: true } }
UPDATE:
So, due to discussion found that the problem was in the property naming. Right to be property: 'idEquipe' not property: 'id_equipe'. So the property names must be same as in the entity, not as the name of the field in the database.
Here's my Matchs entity.
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Matchs
*
* #ORM\Table(name="matchs", indexes={#ORM\Index(name="MATCHS_EQUIPES1_FK", columns={"ID_EQUIPE_EQUIPES"}), #ORM\Index(name="MATCHS_EQUIPES_FK", columns={"ID_EQUIPE"}), #ORM\Index(name="MATCHS_JOURNEE0_FK", columns={"ID_JOURNEE"})})
* #ORM\Entity
*/
class Matchs
{
/**
* #var int
*
* #ORM\Column(name="ID_MATCHS", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idMatchs;
/**
* #var \DateTime
*
* #ORM\Column(name="DATE_MATCHS", type="datetime", nullable=false)
*/
private $dateMatchs;
/**
* #var string|null
*
* #ORM\Column(name="RESUME_MATCHS", type="text", length=65535, nullable=true)
*/
private $resumeMatchs;
/**
* #var string|null
*
* #ORM\Column(name="TITRE_MATCH", type="string", length=255, nullable=true)
*/
private $titreMatch;
/**
* #var int
*
* #ORM\Column(name="SCORE_EQUIPE1", type="integer", nullable=false)
*/
private $scoreEquipe1;
/**
* #var int
*
* #ORM\Column(name="SCORE_EQUIPE2", type="integer", nullable=false)
*/
private $scoreEquipe2;
/**
* #var \Equipes
*
* #ORM\ManyToOne(targetEntity="Equipes")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="ID_EQUIPE_EQUIPES", referencedColumnName="ID_EQUIPE")
* })
*/
private $idEquipeEquipes;
/**
* #var \Equipes
*
* #ORM\ManyToOne(targetEntity="Equipes")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="ID_EQUIPE", referencedColumnName="ID_EQUIPE")
* })
*/
private $idEquipe;
/**
* #var \Journee
*
* #ORM\ManyToOne(targetEntity="Journee")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="ID_JOURNEE", referencedColumnName="ID_JOURNEE")
* })
*/
private $idJournee;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="JoueursEquipe", inversedBy="idMatchs")
* #ORM\JoinTable(name="jouer",
* joinColumns={
* #ORM\JoinColumn(name="ID_MATCHS", referencedColumnName="ID_MATCHS")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="ID_JOUEUR_EQUIPE", referencedColumnName="ID_JOUEUR_EQUIPE")
* }
* )
*/
private $idJoueurEquipe;
/**
* Constructor
*/
public function __construct()
{
$this->idJoueurEquipe = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getIdMatchs()
{
return $this->idMatchs;
}
public function setIdMatchs(int $idMatchs)
{
$this->idMatchs = $idMatchs;
return $this;
}
/**
* Get the value of dateMatchs
*
* #return \DateTime
*/
public function getDateMatchs()
{
return $this->dateMatchs;
}
/**
* Set the value of dateMatchs
*
* #param \DateTime $dateMatchs
*
* #return self
*/
public function setDateMatchs(\DateTime $dateMatchs)
{
$this->dateMatchs = $dateMatchs;
return $this;
}
/**
* Get the value of resumeMatchs
*
* #return string|null
*/
public function getResumeMatchs()
{
return $this->resumeMatchs;
}
/**
* Set the value of resumeMatchs
*
* #param string|null $resumeMatchs
*
* #return self
*/
public function setResumeMatchs($resumeMatchs)
{
$this->resumeMatchs = $resumeMatchs;
return $this;
}
/**
* Get the value of scoreEquipe1
*
* #return int
*/
public function getScoreEquipe1()
{
return $this->scoreEquipe1;
}
/**
* Set the value of scoreEquipe1
*
* #param int $scoreEquipe1
*
* #return self
*/
public function setScoreEquipe1(int $scoreEquipe1)
{
$this->scoreEquipe1 = $scoreEquipe1;
return $this;
}
/**
* Get the value of scoreEquipe2
*
* #return int
*/
public function getScoreEquipe2()
{
return $this->scoreEquipe2;
}
/**
* Set the value of scoreEquipe2
*
* #param int $scoreEquipe2
*
* #return self
*/
public function setScoreEquipe2(int $scoreEquipe2)
{
$this->scoreEquipe2 = $scoreEquipe2;
return $this;
}
/**
* Get the value of idEquipeEquipes
*
* #return \Equipes
*/
public function getIdEquipeEquipes()
{
return $this->idEquipeEquipes;
}
/**
* Set the value of idEquipeEquipes
*
* #param \Equipes $idEquipeEquipes
*
* #return self
*/
public function setIdEquipeEquipes(\Equipes $idEquipeEquipes)
{
$this->idEquipeEquipes = $idEquipeEquipes;
return $this;
}
/**
* Get the value of idEquipe
*
* #return \Equipes
*/
public function getIdEquipe()
{
return $this->idEquipe;
}
/**
* Set the value of idEquipe
*
* #param \Equipes $idEquipe
*
* #return self
*/
public function setIdEquipe(\Equipes $idEquipe)
{
$this->idEquipe = $idEquipe;
return $this;
}
public function __toString()
{
return $this->nomEquipe;
}
/**
* Get the value of idJournee
*
* #return \Journee
*/
public function getIdJournee()
{
return $this->idJournee;
}
/**
* Set the value of idJournee
*
* #param \Journee $idJournee
*
* #return self
*/
public function setIdJournee(\Journee $idJournee)
{
$this->idJournee = $idJournee;
return $this;
}
public function getTitreMatch(): ?string
{
return $this->titreMatch;
}
public function setTitreMatch(string $titreMatch): self
{
$this->titreMatch = $titreMatch;
return $this;
}
/**
* Get the value of idJoueurEquipe
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdJoueurEquipe()
{
return $this->idJoueurEquipe;
}
/**
* Set the value of idJoueurEquipe
*
* #param \Doctrine\Common\Collections\Collection $idJoueurEquipe
*
* #return self
*/
public function setIdJoueurEquipe(\Doctrine\Common\Collections\Collection $idJoueurEquipe)
{
$this->idJoueurEquipe = $idJoueurEquipe;
return $this;
}
public function addIdJoueurEquipe(JoueursEquipe $idJoueurEquipe): self
{
if (!$this->idJoueurEquipe->contains($idJoueurEquipe)) {
$this->idJoueurEquipe[] = $idJoueurEquipe;
}
return $this;
}
public function removeIdJoueurEquipe(JoueursEquipe $idJoueurEquipe): self
{
if ($this->idJoueurEquipe->contains($idJoueurEquipe)) {
$this->idJoueurEquipe->removeElement($idJoueurEquipe);
}
return $this;
}
}
I'm using Sylius 1.0.0-dev and created model called Trainee
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SyliusExtensionBundle\Entity\Product;
use SyliusExtensionBundle\Entity\Order;
use Sylius\Component\Resource\Model\ResourceInterface;
/**
* Trainee
*
* #ORM\Table(name="smartbyte_trainee")
* #ORM\Entity()
*/
class Trainee implements ResourceInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="firstName", type="string", length=255)
*/
private $firstName;
/**
* #var string
*
* #ORM\Column(name="secondName", type="string", length=255)
*/
private $secondName;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=255)
*/
private $phone;
/**
* #var boolean
*
* #ORM\Column(name="is_resignated", type="boolean")
*/
private $isResignated = false;
/**
* #var boolean
*
* #ORM\Column(name="is_present", type="boolean")
*/
private $isPresent = false;
/**
* #var Product
*
* #ORM\ManyToOne(targetEntity="SyliusExtensionBundle\Entity\Product")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $product;
/**
* #var Order
*
* #ORM\ManyToOne(targetEntity="SyliusExtensionBundle\Entity\Order", inversedBy="trainees")
* #ORM\JoinColumn(name="order_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $order;
public function __toString() {
return $this->firstName.' '.$this->secondName;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName
*
* #param string $firstName
* #return Trainee
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set secondName
*
* #param string $secondName
* #return Trainee
*/
public function setSecondName($secondName)
{
$this->secondName = $secondName;
return $this;
}
/**
* Get secondName
*
* #return string
*/
public function getSecondName()
{
return $this->secondName;
}
/**
* Set email
*
* #param string $email
* #return Trainee
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set phone
*
* #param string $phone
* #return Trainee
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* #var string
*/
private $condition;
/**
* Set isResignated
*
* #param boolean $isResignated
* #return Trainee
*/
public function setIsResignated($isResignated)
{
$this->isResignated = $isResignated;
return $this;
}
/**
* Get isResignated
*
* #return boolean
*/
public function getIsResignated()
{
return $this->isResignated;
}
/**
* Set condition
*
* #param string $condition
* #return Trainee
*/
public function setCondition($condition)
{
$this->condition = $condition;
return $this;
}
/**
* Get condition
*
* #return string
*/
public function getCondition()
{
return $this->condition;
}
/**
* Set product
*
* #param Product $product
* #return Trainee
*/
public function setProduct(Product $product = null)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return Product
*/
public function getProduct()
{
return $this->product;
}
/**
* Set order
*
* #param Order $order
* #return Trainee
*/
public function setOrder(Order $order = null)
{
$this->order = $order;
return $this;
}
/**
* Get order
*
* #return Order
*/
public function getOrder()
{
return $this->order;
}
/**
* Set isPresent
*
* #param boolean $isPresent
* #return Trainee
*/
public function setIsPresent($isPresent)
{
$this->isPresent = $isPresent;
return $this;
}
/**
* Get isPresent
*
* #return boolean
*/
public function getIsPresent()
{
return $this->isPresent;
}
}
Then I configure it with config.yml:
sylius_resource:
resources:
app.trainee:
classes:
model: AppBundle\Entity\Trainee
repository: AppBundle\Repository\TraineeRepository
and routing.yml:
app_trainee:
resource: |
alias: app.trainee
section: admin
type: sylius.resource
prefix: /admin
according to the docs. Unfortunately instead of crud template I get :
Unable to find template "/index.html.twig" (looked into: /home/krzysztof/Dokumenty/praca/smartbyte/eventmanager2/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form, /home/krzysztof/Dokumenty/praca/smartbyte/eventmanager2/vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views).
I know there is SyliusAdminBundle with crud templates for resources but by the last version I was using (0.18) sylius evolved much it's completely different from that.
You should compare your routing.yml code to other resources in the AdminBundle routing files.
This is the product declaration in the routing/product.yml file
sylius_admin_product:
resource: |
alias: sylius.product
section: admin
templates: SyliusAdminBundle:Crud
except: ['show']
redirect: update
grid: sylius_admin_product
permission: true
vars:
all:
subheader: sylius.ui.manage_your_product_catalog
templates:
form: SyliusAdminBundle:Product:_form.html.twig
index:
icon: cube
type: sylius.resource
You should probably put the templates: declaration in
I've created an Entity to store some data i'm pulling via an api
When i try to findByOne to see if the entry already exists, i get an error saying the field is not recognised.
I've done a php app/console doctrine:schema:update --force
I can see the table in my mySQL manager with the right fieldname 'StadiumID'
So why cant doctrine find it when i do findByOne();
My Entity Class:
<?php
namespace FantasyPro\DataBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Stadium
*
* #ORM\Table("fp_stadium")
* #ORM\Entity(repositoryClass="FantasyPro\DataBundle\Entity\StadiumRepository")
*/
class Stadium
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="StadiumID", type="integer", length=2, nullable=false, unique=true)
*/
private $stadiumID;
/**
* #var string
*
* #ORM\Column(name="Name", type="string", length=100, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="City", type="string", length=50, nullable=false)
*/
private $city;
/**
* #var string
*
* #ORM\Column(name="State", type="string", length=10, nullable=true)
*/
private $state;
/**
* #var string
*
* #ORM\Column(name="Country", type="string", length=2, nullable=false)
*/
private $country;
/**
* #var integer
*
* #ORM\Column(name="Capacity", type="integer", length=32, nullable=true)
*/
private $capacity;
/**
* #var string
*
* #ORM\Column(name="PlayingSurface", type="string", length=50, nullable=true)
*/
private $playingSurface;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set stadiumID
*
* #param integer $stadiumID
* #return Stadium
*/
public function setStadiumID($stadiumID)
{
$this->stadiumID = $stadiumID;
return $this;
}
/**
* Get stadiumID
*
* #return integer
*/
public function getStadiumID()
{
return $this->stadiumID;
}
/**
* Set name
*
* #param string $name
* #return Stadium
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set city
*
* #param string $city
* #return Stadium
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* #return string
*/
public function getCity()
{
return $this->city;
}
/**
* Set state
*
* #param string $state
* #return Stadium
*/
public function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Get state
*
* #return string
*/
public function getState()
{
return $this->state;
}
/**
* Set country
*
* #param string $country
* #return Stadium
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set capacity
*
* #param integer $capacity
* #return Stadium
*/
public function setCapacity($capacity)
{
$this->capacity = $capacity;
return $this;
}
/**
* Get capacity
*
* #return integer
*/
public function getCapacity()
{
return $this->capacity;
}
/**
* Set playingSurface
*
* #param string $playingSurface
* #return Stadium
*/
public function setPlayingSurface($playingSurface)
{
$this->playingSurface = $playingSurface;
return $this;
}
/**
* Get playingSurface
*
* #return string
*/
public function getPlayingSurface()
{
return $this->playingSurface;
}
}
The code i'm using to add the data if it does not exist and to update it if it does exist:
<?php
namespace FantasyPro\DataBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FantasyPro\DataBundle\Entity\Stadium;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('DataBundle:Default:index.html.twig', array('name' => $name));
}
public function updateStadiumAction(){
//get list of stadiums
$client = $this->container->get('fantasyapi');
$stadiumData = $client->Stadiums();
//var_dump($stadiumData);
//get the entity manager
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('DataBundle:Stadium');
$log = $stadiumData;
foreach($stadiumData as $stadium){
// Get the current stadium in the list
$criteria = array("StadiumID" =>$stadium['StadiumID']);
var_dump($criteria);
$storedStadium = $repo->FindOneBy($criteria);
if (!$storedStadium) {
/* throw $this->createNotFoundException(
'No product found for id '.$stadium['StadiumID']
);*/
//no stadium exists with the StadiumID passed
//create a new entry
$entry = new Stadium();
$entry->setStadiumID($stadium['StadiumID']);
$entry->setName($stadium['Name']);
$entry->setCity($stadium['City']);
$entry->setState($stadium['State']);
$entry->setCountry($stadium['Country']);
$entry->setCapacity($stadium['Capacity']);
$entry->setPlayingSurface($stadium['PlayingSurface']);
$em->persist($entry);
$log .= 'Added New Stadium: '.$stadium['StadiumID'].' : '.$stadium['Name'].'<br>';
}else{
$storedStadium->setStadiumID($stadium['StadiumID']);
$storedStadium->setName($stadium['Name']);
$storedStadium->setCity($stadium['City']);
$storedStadium->setState($stadium['State']);
$storedStadium->setCountry($stadium['Country']);
$storedStadium->setCapacity($stadium['Capacity']);
$storedStadium->setPlayingSurface($stadium['PlayingSurface']);
$em->persist($storedStadium);
$log .= 'Updated Stadium: '.$stadium['StadiumID'].' : '.$stadium['Name'].'<br>';
}
}
//$em->flush();
return $this->render('DataBundle:Default:index.html.twig', array('log' => $log));
}
}
The property name is actually:
private $stadiumID;
So you should do :
$repo->findOneBy(array('stadiumID' => $value));
so change this row:
$criteria = array("StadiumID" =>$stadium['StadiumID']);
to this:
$criteria = array("stadiumID" =>$stadium['StadiumID']);
Doctrine's main role is to connect your application layer(entites) to the database layer(tables). So doctrine tries to translate request comming from the application layer to the database. Even if you named your field in the database "StadiumID"or "table_name_snake_case", when you call findOneBy(array($property => $value)), doctrine expects $property to refer to the property name, and it will translate this to SQL to something like 'SELECT FROM .... where StadiumID = :value'
For others who still have the problem,
make sur that you have puted the sign '=>' instead of ',' when calling the function findOneBy(...)
So instead of :
findOneBy(["code" , "Code-Example"]);
do that :
findOneBy(["code" => "Code-Example"]);
Also, make sure the doctrine naming strategy is specified:
doctrine:
orm:
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
this is the doctrine's default naming strategy. This way doctrine knows how to map Entity property names to column names.
Note that, naming strategy configuration might be in different levels of doctrine configuration. For example, in another repo it is configured like this:
doctrine:
orm:
default_entity_manager: shopping
entity_managers:
shopping:
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
I tried very hard to get the KNP Paginator to work.
I only want to oder an Entity to the id, but the pagination accept all the params but does noting with it!
Here´s my code:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
The Controller class:
class StartController extends Controller
{
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$dql = "SELECT a FROM MainArtBundle:Art a";
$query = $em->createQuery($dql);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$request->query->get('page', 1) /*page number*/,
8 /*limit per page*/
);
$pagination->setUsedRoute('homepage');
if (!$pagination) {
throw $this->createNotFoundException('Unable to find Art entities.');
}
return $this->render('MainShowBundle:Default:index.html.twig', array(
'pagination' => $pagination,
));
}
The Twig Template:
<li>{{ knp_pagination_sortable(pagination, 'Oldest', 'a.id', {'direction': 'desc'}) }}</li>
<li>{{ knp_pagination_sortable(pagination, 'Newest', 'a.id', {'direction': 'asc'}) }}</li>
The ArtEntity (the entire Entity because perhaps the mistake is caused by the entity, can it be)
<?php
namespace Main\ArtBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Main\LikeBundle\Entity\Thumb;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\Request;
/**
* Art
*
* #ORM\Table(name="art")
* #ORM\Entity(repositoryClass="Main\ArtBundle\Entity\ArtRepository")
*/
class Art
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $locale
*
* #ORM\Column(name="locale", type="string", length=5, nullable=false)
*/
protected $locale;
/**
* #var arrayCollection $user
*
* #ORM\ManyToOne(targetEntity="Main\UserBundle\Entity\User", inversedBy="arts")
*
*/
protected $user;
/**
* #var \Doctrine\Common\Collections\ArrayCollection $visits
*
* #ORM\OneToMany(targetEntity="Main\ArtBundle\Entity\ArtVisit", mappedBy="art", fetch="EXTRA_LAZY")
*
*/
protected $visits;
/**
* #var \Doctrine\Common\Collections\ArrayCollection $tags
*
* #ORM\ManyToMany(targetEntity="Tags", inversedBy="arts", cascade={"persist"})
*/
protected $tags;
/**
* #var \Doctrine\Common\Collections\ArrayCollection $feature_partner
* #ORM\ManyToMany(targetEntity="Main\UserBundle\Entity\User", inversedBy="feature_partner")
*
*/
protected $feature_partner;
/**
* #var string $headline
*
* #Assert\NotBlank()
*
* #ORM\Column(type="string", length=255, unique=false, nullable=false)
*/
protected $headline;
/**
* #var \Main\StorageBundle\Entity\Image
*
* #ORM\OneToOne(targetEntity="Main\StorageBundle\Entity\Image")
* #ORM\Column(nullable=true)
*/
protected $image;
/**
* #var string $content
*
* #Assert\NotBlank()
*
* #ORM\Column(type="text", unique=false, nullable=false)
*/
protected $content;
/**
* #var string $description
*
* #ORM\Column(type="text", unique=false, nullable=true)
*/
protected $description;
/**
* #var datetime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var datetime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* #var datetime $contentChanged
*
* #ORM\Column(name="content_changed", type="datetime", nullable=true)
* #Gedmo\Timestampable(on="change", field={"headline", "content"})
*/
private $contentChanged;
/**
* #var integer $viewed
*
* #ORM\Column(name="viewed", type="integer", nullable=true)
*/
private $viewed;
/**
* #var object $CommentThread
*
*/
private $thread_id;
/**
* #var \Doctrine\Common\Collections\ArrayCollection $thumbs
*
* #ORM\OneToMany(targetEntity="Main\LikeBundle\Entity\Thumb", mappedBy="entity", fetch="EXTRA_LAZY")
*/
private $thumbs;
/**
* Constructor.
*/
public function __construct()
{
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
$this->feature_partner = new \Doctrine\Common\Collections\ArrayCollection();
$this->thumbs = new \Doctrine\Common\Collections\ArrayCollection();
$this->commentThread = new \Main\ArtBundle\Entity\CommentThread($this->getId());
/*$request = new Request();
$this->locale = $request->getLocale()*/;
}
/**
* #return string
*/
public function __toString()
{
return $this->getHeadline();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set user
*
* #param integer $userId
* #return Art
*/
public function setUserId($userId)
{
$this->user = $userId;
return $this;
}
/**
* Get user
*
* #return integer
*/
public function getUserId()
{
return $this->user;
}
/**
* Set tags
*
* #param integer $tags
* #return Art
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return integer
*/
public function getTags()
{
return $this->tags;
}
/**
* Set headline
*
* #param string $headline
* #return Art
*/
public function setHeadline($headline)
{
$this->headline = $headline;
return $this;
}
/**
* Get headline
*
* #return string
*/
public function getHeadline()
{
return $this->headline;
}
/**
* Set content
*
* #param string $content
* #return Art
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set created
*
* #param \DateTime $created
* #return Art
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Art
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set contentChanged
*
* #param \DateTime $contentChanged
* #return Art
*/
public function setContentChanged($contentChanged)
{
$this->contentChanged = $contentChanged;
return $this;
}
/**
* Get contentChanged
*
* #return \DateTime
*/
public function getContentChanged()
{
return $this->contentChanged;
}
/**
* Set feature_partner
*
* #param integer $featurePartner
* #return Art
*/
public function setFeaturePartner($featurePartner)
{
$this->feature_partner = $featurePartner;
return $this;
}
/**
* Get feature_partner
*
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getFeaturePartner()
{
return $this->feature_partner;
}
/**
* Add feature_partner
*
* #param \Main\UserBundle\Entity\User $featurePartner
* #return Art
*/
public function addFeaturePartner(\Main\UserBundle\Entity\User $featurePartner)
{
$this->feature_partner[] = $featurePartner;
return $this;
}
/**
* Remove feature_partner
*
* #param \Main\UserBundle\Entity\User $featurePartner
*/
public function removeFeaturePartner(\Main\UserBundle\Entity\User $featurePartner)
{
$this->feature_partner->removeElement($featurePartner);
}
/**
* Set description
*
* #param string $description
* #return Art
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set user
*
* #param \Main\UserBundle\Entity\User $user
* #return Art
*/
public function setUser(\Main\UserBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \Main\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Add tags
*
* #param \Main\ArtBundle\Entity\Tags $tags
* #return Art
*/
public function addTag(\Main\ArtBundle\Entity\Tags $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* Remove tags
*
* #param \Main\ArtBundle\Entity\Tags $tags
*/
public function removeTag(\Main\ArtBundle\Entity\Tags $tags)
{
$this->tags->removeElement($tags);
}
/**
* Add visits
*
* #param \Main\ArtBundle\Entity\ArtVisit $visits
* #return Art
*/
public function addVisit(\Main\ArtBundle\Entity\ArtVisit $visits)
{
$this->visits[] = $visits;
return $this;
}
/**
* Remove visits
*
* #param \Main\ArtBundle\Entity\ArtVisit $visits
*/
public function removeVisit(\Main\ArtBundle\Entity\ArtVisit $visits)
{
$this->visits->removeElement($visits);
}
/**
* Get visits
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVisits()
{
return $this->visits;
}
/**
* Set locale
*
* #param string $locale
* #return Art
*/
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* Get locale
*
* #return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* Set image
*
* #param \Main\StorageBundle\Entity\Image $image
* #return Art
*/
public function setImage(\Main\StorageBundle\Entity\Image $image = null)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return \Main\StorageBundle\Entity\Image
*/
public function getImage()
{
return $this->image;
}
/**
* Set viewed
*
* #param integer $viewed
* #return Art
*/
public function setViewed($viewed)
{
$this->viewed = $viewed;
return $this;
}
/**
* Get viewed
*
* #return integer
*/
public function getViewed()
{
return $this->viewed;
}
/**
* Set thumbs
*
* #param \Main\LikeBundle\Entity\Thumb $thumbs
* #return Art
*/
public function setThumbs(Thumb $thumbs = null)
{
$this->thumbs = $thumbs;
return $this;
}
/**
* Get thumbs
*
* #return \Doctrine\Common\Collections\ArrayCollection $thumbs
*/
public function getThumbs()
{
return $this->thumbs;
}
/**
* Add thumb
*
* #param \Main\LikeBundle\Entity\Thumb $thumb
* #return $this $thumbs
*/
public function addThumb(Thumb $thumb)
{
$this->thumbs[] = $thumb;
return $this;
}
/**
* Remove thumbs
*
* #param \Main\LikeBundle\Entity\Thumb $thumbs
*/
public function removeThumb(\Main\LikeBundle\Entity\Thumb $thumbs)
{
$this->thumbs->removeElement($thumbs);
}
/**
* Count all Thumbs of the piece of art.
*/
public function countAllThumbs() {
return $this->thumbs->count();
}
/**
* Check weather a user has thumbed a piece of art or not.
*/
public function isThumbed($user) {
// my first Closure :D
$p = function($key, $element) use ($user) {
return $element->getUser() == $user;
};
return $this->thumbs->exists($p);
}
/**
* Get the thumb object from a special user.
*/
public function getThumbFromUser ($user) {
$p = function($element) use ($user) {
return $element->getUser() == $user;
};
return $this->thumbs->filter($p);
}
}
The KNP Pagination Configuration (in config.yml)
knp_paginator:
page_range: 5 # default page range used in pagination control
default_options:
page_name: page # page query parameter name
sort_field_name: sort # sort field query parameter name
sort_direction_name: direction # sort direction query parameter name
distinct: true # ensure distinct results, useful when ORM queries are using GROUP BY statements
template:
pagination: ::Pagination\twitter_bootstrap_v3_pagination.html.twig # sliding pagination controls template
sortable: ::Pagination\sortable_link.html.twig # sort link template
I have dumped the pagination object in the controller and in the template as well. Everytime the params are there (direction= asc or desc) something like this is in the url:
?sort=a.id&direction=desc&page=1
but if I click on the link to change the direction: nothing change!!
I believe the knp pagination has a bug! Or I am very stupid ;)
If anyone can help me, I will be very happy!
Greetings Michael
For me, I created a new file knp_paginator.yaml and not knp_paginator.yml and I added this configuration and evrything works:
knp_paginator:
page_range: 5 # number of links shown in the pagination menu (e.g: you have 10 pages, a page_range of 3, on the 5th page you'll see links to page 4, 5, 6)
default_options:
page_name: page # page query parameter name
sort_field_name: sort # sort field query parameter name
sort_direction_name: direction # sort direction query parameter name
distinct: true # ensure distinct results, useful when ORM queries are using GROUP BY statements
filter_field_name: filterField # filter field query parameter name
filter_value_name: filterValue # filter value query parameter name
template:
pagination: '#KnpPaginator/Pagination/twitter_bootstrap_v4_pagination.html.twig' # sliding pagination controls template
sortable: '#KnpPaginator/Pagination/sortable_link.html.twig' # sort link template
filtration: '#KnpPaginator/Pagination/filtration.html.twig' # filters template
I am trying to use the Timestampable behaviour from Doctrine Extensions, I installed StofDoctrineExtensionsBundle to help me with that. But when I make my YML scheme and run the generate entities command, everything runs without errors, but in the generated php class no Gedmo/DoctrineExtensions annotations appear. What am I doing wrong?
This is the YML file I use for the simple issue tracker I want to make (Issue.orm.yml):
Theta\IssueTrackerBundle\Entity\Issue:
type: entity
table: issues
id:
id:
type: integer
generator:
strategy: AUTO
fields:
category:
type: string
length: 16
created_at:
type: datetime
gedmo:
timestampable:
on: create
updated_at:
type: datetime
gedmo:
timestampable:
on: update
closed_at:
type: datetime
gedmo:
timestampable
title:
type: string
length: 64
oneToOne:
user_id:
targetEntity: ThetaUserBundle\User
assigned_to:
targetEntity: ThetaUserBundle\User
This is the generated php class (Issue.php):
namespace Theta\IssueTrackerBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Issue
*/
class Issue
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $category;
/**
* #var \DateTime
*/
private $created_at;
/**
* #var \DateTime
*/
private $updated_at;
/**
* #var \DateTime
*/
private $closed_at;
/**
* #var string
*/
private $title;
/**
* #var \ThetaUserBundle\User
*/
private $user_id;
/**
* #var \ThetaUserBundle\User
*/
private $assigned_to;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set category
*
* #param string $category
* #return Issue
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return string
*/
public function getCategory()
{
return $this->category;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return Issue
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* #param \DateTime $updatedAt
* #return Issue
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set closed_at
*
* #param \DateTime $closedAt
* #return Issue
*/
public function setClosedAt($closedAt)
{
$this->closed_at = $closedAt;
return $this;
}
/**
* Get closed_at
*
* #return \DateTime
*/
public function getClosedAt()
{
return $this->closed_at;
}
/**
* Set title
*
* #param string $title
* #return Issue
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set user_id
*
* #param \ThetaUserBundle\User $userId
* #return Issue
*/
public function setUserId(\ThetaUserBundle\User $userId = null)
{
$this->user_id = $userId;
return $this;
}
/**
* Get user_id
*
* #return \ThetaUserBundle\User
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set assigned_to
*
* #param \ThetaUserBundle\User $assignedTo
* #return Issue
*/
public function setAssignedTo(\ThetaUserBundle\User $assignedTo = null)
{
$this->assigned_to = $assignedTo;
return $this;
}
/**
* Get assigned_to
*
* #return \ThetaUserBundle\User
*/
public function getAssignedTo()
{
return $this->assigned_to;
}
}
The timestampable behaviour does not appear in the php class, and I don't understand why. I followed the instructions for installing the StofDoctrineExtensionsBundle to the letter, and it seems to be installed correctly, but it doesn't do anything. I am using Symfony 2.2.
So my question: am I expecting something that is not supposed to happen, or am I doing something wrong?
Thanks for your help.
Luc
Not sure if its works the same way for StofDoctrineExtensions but generally you would need to put the lifecyccallbacks in your yml.
lifecycleCallbacks:
postPersist: doSomething
# callback # method in entity
And then the annotations and the method name would match this.