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.
Related
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 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.
am working on symfony2 and am geting this error:
No mapping file found named 'Acme.BlogBundle.Entity.Posts.php' for
class 'Acme\BlogBundle\Entity\Posts'. 500 Internal Server Error -
MappingException
I generate Entity php app/console doctrine:generate:entity
Name of entity: AcmeBlogBundle:Post
Format: php
All that i put in Acme:BlogBundle:Entity directory.
This is my Entity Post class with getter and setter methds:
<?php
namespace Acme\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Posts
*/
class Posts
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $title;
/**
* #var string
*/
private $shortText;
/**
* #var string
*/
private $longText;
/**
* #var string
*/
private $author;
/**
* #var \DateTime
*/
private $dateCreated;
/**
* #var \DateTime
*/
private $dateModified;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Posts
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set shortText
*
* #param string $shortText
* #return Posts
*/
public function setShortText($shortText)
{
$this->shortText = $shortText;
return $this;
}
/**
* Get shortText
*
* #return string
*/
public function getShortText()
{
return $this->shortText;
}
/**
* Set longText
*
* #param string $longText
* #return Posts
*/
public function setLongText($longText)
{
$this->longText = $longText;
return $this;
}
/**
* Get longText
*
* #return string
*/
public function getLongText()
{
return $this->longText;
}
/**
* Set author
*
* #param string $author
* #return Posts
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set dateCreated
*
* #param \DateTime $dateCreated
* #return Posts
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Set dateModified
*
* #param \DateTime $dateModified
* #return Posts
*/
public function setDateModified($dateModified)
{
$this->dateModified = $dateModified;
return $this;
}
/**
* Get dateModified
*
* #return \DateTime
*/
public function getDateModified()
{
return $this->dateModified;
}
}
In my controller i first set Post Entity after definig namespace of controller.
use Acme\BlogBundle\Entity\Posts;
After that i create method
public function AddAction()
{
// $post = Acme\BlogBundle\Entity\Posts()
$posts = new Posts();
$posts->setTitle('Test Title');
$em = $this->getDoctrine()->getManager();
$em->persist($posts);
$em->flush();
}
Here is and Stack Trace output
[1] Doctrine\Common\Persistence\Mapping\MappingException: No mapping
file found named 'Acme.BlogBundle.Entity.Posts.php' for class
'Acme\BlogBundle\Entity\Posts'.
at n/a
in /var/www/html/Symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php
line 74
at Doctrine\Common\Persistence\Mapping\MappingException::mappingFileNotFound('Acme\BlogBundle\Entity\Posts',
'Acme.BlogBundle.Entity.Posts.php')
in /var/www/html/Symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/DefaultFileLocator.php
line 117
at Doctrine\Common\Persistence\Mapping\Driver\DefaultFileLocator->findMappingFile('Acme\BlogBundle\Entity\Posts')
in /var/www/html/Symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/PHPDriver.php
line 59
at Doctrine\Common\Persistence\Mapping\Driver\PHPDriver->loadMetadataForClass('Acme\BlogBundle\Entity\Posts',
object(ClassMetadata))
in /var/www/html/Symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php
line 104
at Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain->loadMetadataForClass('Acme\BlogBundle\Entity\Posts',
object(ClassMetadata))
in /var/www/html/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php
line 113
at Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata(object(ClassMetadata),
null, false, array())
in /var/www/html/Symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php
line 302
at Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata('Acme\BlogBundle\Entity\Posts')
in /var/www/html/Symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php
line 205
at Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor('Acme\BlogBundle\Entity\Posts')
in /var/www/html/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php
line 268
at Doctrine\ORM\EntityManager->getClassMetadata('Acme\BlogBundle\Entity\Posts')
in /var/www/html/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php
line 1580
at Doctrine\ORM\UnitOfWork->doPersist(object(Posts), array('000000000d824498000000009cdc8511' => object(Posts)))
in /var/www/html/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php
line 1555
at Doctrine\ORM\UnitOfWork->persist(object(Posts))
in /var/www/html/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php
line 565
at Doctrine\ORM\EntityManager->persist(object(Posts))
in /var/www/html/Symfony/src/Acme/BlogBundle/Controller/DefaultController.php
line 23
at Acme\BlogBundle\Controller\DefaultController->indexAction()
in line
at call_user_func_array(array(object(DefaultController), 'indexAction'), array())
in /var/www/html/Symfony/app/bootstrap.php.cache line 2815
at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request),
'1')
in /var/www/html/Symfony/app/bootstrap.php.cache line 2789
at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1',
true)
in /var/www/html/Symfony/app/bootstrap.php.cache line 2918
at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request),
'1', true)
in /var/www/html/Symfony/app/bootstrap.php.cache line 2220
at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
in /var/www/html/Symfony/web/app_dev.php line 28
Update:
New Entity Test:
<?php
// src/Acme/BlogBundle/Entity/Test.php
namespace Acme\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
*/
class Test
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="short_text", type="string", length=255)
*/
private $shortText;
/**
* #var string
*
* #ORM\Column(name="long_text", type="text")
*/
private $longText;
/**
* #var \DateTime
*
* #ORM\Column(name="date_created", type="datetime")
*/
private $dateCreated;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Test
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set shortText
*
* #param string $shortText
* #return Test
*/
public function setShortText($shortText)
{
$this->shortText = $shortText;
return $this;
}
/**
* Get shortText
*
* #return string
*/
public function getShortText()
{
return $this->shortText;
}
/**
* Set longText
*
* #param string $longText
* #return Test
*/
public function setLongText($longText)
{
$this->longText = $longText;
return $this;
}
/**
* Get longText
*
* #return string
*/
public function getLongText()
{
return $this->longText;
}
/**
* Set dateCreated
*
* #param \DateTime $dateCreated
* #return Test
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
}
Again the some error
$ php app/console doctrine:generate:entities AcmeBlogBundle
Generating entities for bundle "AcmeBlogBundle"
[RuntimeException]
Bundle "AcmeBlogBundle" does not contain any mapped entities.
doctrine:generate:entities [--path="..."] [--no-backup] name
You should add mapping information for fields. Read more
Like this:
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
I made the mistake of adding a new Entity through console with a mapping type of 'php' instead of my default 'annotations'. Immediately without even touching the generated class my site wouldn't load. It threw this MappingException for my user class.
I removed the new Entity class thinking that would fix it, and everything else I could think of. Then I looked in my app/Resources/config directory. There was a new directory called Doctrine. It contained a mapping file for the Entity that caused the issue. When I removed this directory and file, the Exception was gone.
If you want to use annotations to defining your mapping, just select the option "annotations" when you generate your entity.
Although this question is quite old I don't want to keep a secret how I solved it. It seems that I had an old mapping files reference in the cache because I moved it to another folder. Clearing the cache solved the issue for me.
I'm getting this error on my production environnent: (from prod.log)
[2012-01-30 17:00:51] request.CRITICAL: Doctrine\ORM\Mapping\MappingException: Class Gitek\UdaBundle\Entity\Curso is not a valid entity or mapped super class. (uncaught exception) at /home/uda/shared/vendor/doctrine/lib/Doctrine/ORM/Mapping/MappingException.php line 142 [] []
But in my development environnent everything works fine.
And this is my Curso entity:
<?php
namespace Gitek\UdaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Gitek\UdaBundle\Entity\Curso
*
* #ORM\Table(name="Curso")
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="Gitek\UdaBundle\Entity\CursoRepository")
*/
class Curso
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $nombre
*
* #ORM\Column(name="nombre", type="string", length=255)
*/
private $nombre;
/**
* #var string $version
*
* #ORM\Column(name="version", type="string", length=255, nullable=true)
*/
private $version;
/**
* #var integer $orden
*
* #ORM\Column(name="orden", type="integer", nullable=true, nullable=true)
*/
private $orden;
/**
* #var integer $tiempo
*
* #ORM\Column(name="tiempo", type="integer", nullable=true, nullable=true)
*/
private $tiempo;
/**
* #ORM\OneToMany(targetEntity="Detcurso", mappedBy="curso", cascade={"remove"})
* #ORM\OrderBy({"orden" = "ASC"})
*/
private $detcursos;
/**
* #ORM\OneToMany(targetEntity="Historial", mappedBy="curso", cascade={"remove"})
*/
private $historiales;
/**
* #ORM\Column(type="datetime")
*/
protected $created;
/**
* #ORM\Column(type="datetime")
*/
protected $updated;
public function __construct()
{
$this->detcursos = new \Doctrine\Common\Collections\ArrayCollection();
$this->setCreated(new \DateTime());
$this->setUpdated(new \DateTime());
}
public function __toString()
{
return $this->getNombre();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* #param string $nombre
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set version
*
* #param string $version
*/
public function setVersion($version)
{
$this->version = $version;
}
/**
* Get version
*
* #return string
*/
public function getVersion()
{
return $this->version;
}
/**
* Set orden
*
* #param integer $orden
*/
public function setOrden($orden)
{
$this->orden = $orden;
}
/**
* Get orden
*
* #return integer
*/
public function getOrden()
{
return $this->orden;
}
/**
* Set created
*
* #param datetime $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* Get created
*
* #return datetime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param datetime $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* Get updated
*
* #return datetime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Add detcursos
*
* #param Gitek\UdaBundle\Entity\Detcurso $detcursos
*/
public function addDetcurso(\Gitek\UdaBundle\Entity\Detcurso $detcursos)
{
$this->detcursos[] = $detcursos;
}
/**
* Get detcursos
*
* #return Doctrine\Common\Collections\Collection
*/
public function getDetcursos()
{
return $this->detcursos;
}
/**
* Add historiales
*
* #param Gitek\UdaBundle\Entity\Historial $historiales
*/
public function addHistorial(\Gitek\UdaBundle\Entity\Historial $historiales)
{
$this->historiales[] = $historiales;
}
/**
* Get historiales
*
* #return Doctrine\Common\Collections\Collection
*/
public function getHistoriales()
{
return $this->historiales;
}
/**
* Get historial
*
* #return Doctrine\Common\Collections\Collection
*/
public function getHistorial()
{
return $this->historial;
}
/**
* Set tiempo
*
* #param integer $tiempo
*/
public function setTiempo($tiempo)
{
$this->tiempo = $tiempo;
}
/**
* Get tiempo
*
* #return integer
*/
public function getTiempo()
{
return $this->tiempo;
}
}
As I said, in app_dev works correctly.
You can have different metadata cache configurations depending on which environment you are in. For example apc can cause troubles if not correctly refreshed.
Anyway, you will have to warmup your cache in prod environment, like this:
php app/console cache:clear --env=prod
If this still doesn't work, try to change your doctrine cache configuration:
orm:
auto_generate_proxy_classes: false
default_entity_manager: default
entity_managers:
default:
metadata_cache_driver: array
query_cache_driver: array
result_cache_driver: array
This will use the array cache driver, which is refreshed once at every request.
You shouldn't use this in production, but it can help you to understand where you problem comes from.
In my case the problem was solved by changing my servers cache from eAccelerator to APC. Apparently eAccelerator strips all the comments from files which breaks your annotations.