Symfony SoftDeleteable - php

I have entity and I use
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
and when I delete some entity in my database I have my entity and in field deletedAt I have time when I delete entity and this is ok. But Now I need find all deleteAt entity? I create QB
$qb = $this->getEntityManager()->createQueryBuilder('d');
$qb
->select('d')
->from('ArtelProfileBundle:Project', 'd')
->where('d.deletedAt IS NOT NULL');
$count = $qb->getQuery()->getResult();
$query = $qb->getQuery();
$results = $query->getResult();
return [$results, $count];
I have 0 entity, why and how find entity ?
UPDATE
In my controller
class ProjectController extends FOSRestController
{
public function getProjectsAction(ParamFetcher $paramFetcher)
{
$manager = $this->getDoctrine()->getManager();
if($paramFetcher->get('status'))
{
$manager->getFilters()->disable('soft-deleteable');
$queryBuilder = $manager->getRepository('ArtelProfileBundle:Project')->findForStatusProject($paramFetcher, $this->getUser());
}
and I have error
Filter 'soft-deleteable' is not enabled.
my entity
/**
* Project
*
* #ORM\Table(name="project")
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
* #ORM\Entity(repositoryClass="Artel\ProfileBundle\Entity\Repository\ProjectRepository")
* #ExclusionPolicy("all")
*/
class Project
{
/////
/**
* #var \DateTime $deletedAt
*
* #ORM\Column(name="deleted_at", type="datetime", nullable=true)
* #Type("DateTime")
* #Expose()
*/
protected $deletedAt;
help please

Solved
it is simply a mismatch between the name I use in my config and in my code
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
stof_doctrine_extensions:
default_locale: "%locale%"
orm:
default:
timestampable: true
sluggable: true
softdeleteable: true
and then in my action I do
$manager->getFilters()->disable('softdeleteable');
And have the entity which I deleted

It's been a while, debugging the FilterColletion Class I found a simpler solution
$manager->getFilters()->disable('soft_deleteable'); //(using dash instead of minus sing, the last one is parsed to a dash )

Related

EasyAdminBundle and VichUploaderBundle - Error: The expected argument of type"", "Symfony\Component\HttpFoundation\File\UploadedFile" given

I'm using EasyAdminBundle for entity management and to upload images I want to useVichUploaderBundle.
Following the documentation configure the Bundle:
https://github.com/javiereguiluz/EasyAdminBundle/blob/master/Resources/doc/integration/vichuploaderbundle.rst
I do not use annotations but yml as described in the documentation:
https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/mapping/yaml.md
My code looks like this:
//app/config/config.yml
vich_uploader:
db_driver: orm
mappings:
torneo_images:
uri_prefix: '%app.path.torneo_images%'
upload_destination: '%kernel.root_dir%/../web/uploads/images/torneos'
..........
easy_admin:
form:
fields:
- logo
- { property: 'imageFile', type: 'file' }
The yml configuration file:
//BackendBundle/Resources/config/doctrine/Torneos.orm.yml
......
logo:
type: string
nullable: true
length: 255
options:
fixed: false
imageFile:
mapping: torneo_images
filename_property: logo
Add to Entity
//BackendBundle/Entity/Torneos.orm.yml
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\PropertyMapping as Vich;
namespace BackendBundle\Entity;
.......
/**
* #var string
*/
private $logo;
/**
* #var File
*/
private $imageFile;
.......
/**
* Set logo
*
* #param string $logo
*
* #return Torneos
*/
public function setLogo($logo)
{
$this->logo = $logo;
return $this;
}
/**
* Get logo
*
* #return string
*/
public function getLogo()
{
return $this->logo;
}
/**
* 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 $image
*
* #return Torneos
*/
public function setImageFile(File $logo = null)
{
$this->imageFile = $logo;
// VERY IMPORTANT:
// 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
//if ($image) {
// if 'updatedAt' is not defined in your entity, use another property
// $this->updatedAt = new \DateTime('now');
//}
return $this;
}
/**
* #return File|null
*/
public function getImageFile()
{
return $this->imageFile;
}
Also add this code (I'm not sure if it's correct)
//BackendBundle/Resources/config/vich_uploader/Torneos.orm.yml
BackendBundle\Entity\Torneos:
imageFile:
mapping: torneo_images
filename_property: logo
Can anyone give me some idea to fix it?
The solution was quite simple.
The error occurs because the use are placed before thenamespace in the controller.
namespace BackendBundle\Entity;
Regards

Groups Annotations don't works

Symfony 3.1.7 + FOSRestBundle latest version
<?php
namespace PM\ApiBundle\Controller;
...
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;
class ArticlesController extends FOSRestController
{
/**
* #ApiDoc(
* section="articles",
* resource=true,
* description="Get articles published"
* )
* #Rest\View(serializerGroups={"article"})
* #Rest\Get("/articles")
*/
public function getArticlesAction(Request $request)
{
$articles = $this->getDoctrine()
->getManager()
->getRepository('PMPlatformBundle:Article')
->findAllDateDesc();
/* #var $articles Article[] */
return $articles;
}
Then in my Article entity I added this annotation #Groups({"article"}) with the right use statement.
Whit default serializer I get :
[
[],
[]
]
Whit JMS serializer (bundle) I get :
{
"0": {},
"1": {}
}
(I have two articles in db)
it seems like the "article" group is not recognized. When I use the default serializer whithout this annotations I get a circular error.
What's wrong ?
[EDIT] Same behavior with
/**
* #ApiDoc(
* section="articles",
* resource=true,
* description="Get articles published"
* )
* #Rest\View()
* #Rest\Get("/articles")
*/
public function getArticlesAction(Request $request)
{
$context = new Context();
$context->addGroup('article');
$articles = $this->getDoctrine()
->getManager()
->getRepository('PMPlatformBundle:Article')
->findAllDateDesc();
/* #var $articles Article[] */
$view = $this->view($articles, 200);
$view->setContext($context);
return $view;
}
The response still empty.
You can keep the default serializer of symfony. No need of JMSSerializer.
You may have forgotten to activate the annotations of serializer in config.yml (https://symfony.com/doc/current/serializer.html#using-serialization-groups-annotations)
#app/config/config.yml
framework:
....
serializer: { enable_annotations: true }
It is necessary to force the view_response_listener in config.yml (http://symfony.com/doc/master/bundles/FOSRestBundle/3-listener-support.html, http://symfony.com/doc/master/bundles/FOSRestBundle/view_response_listener.html)
#app/config/config.yml
fos_rest:
view:
view_response_listener: 'force'
That should work !
Ok I fixed it using JMS serializer like this :
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerBuilder;
class ArticlesController extends FOSRestController
{
/**
* #ApiDoc(
* section="articles",
* resource=true,
* description="Get articles published"
* )
* #Rest\View()
* #Rest\Get("/articles")
*/
public function getArticlesAction(Request $request)
{
$serializer = SerializerBuilder::create()->build();
$articles = $this->getDoctrine()
->getManager()
->getRepository('PMPlatformBundle:Article')
->findAllDateDesc();
/* #var $articles Article[] */
return $serializer->serialize($articles, 'json', SerializationContext::create()->setGroups(array('article')));
}
Now the groups annotations works fine.
try php bin/console cache:clear
Using your suggested answer
$serializer = SerializerBuilder::create()->build();
return $serializer->serialize($collection, 'json', SerializationContext::create()->setGroups(['group']));
returns JSON as string to me. To solve your problem, you have to have the following in your config.yml file:
jms_serializer:
metadata:
auto_detection: true
this is how it recognises mappings that you specify with your annotations in Entity files. More info on it here: docs. Having that, you can use the #View(serializerGroups={"group"}) annotation as you wanted.
P.S. Symfony 3.2.2; JMSSerializer 1.1; FOSRestBundle 2.1

Doctrine: update column on insert in other table

I have 2 entities: Service and Session with one-to-many relationship
class Service{
/**
* #var int
*
* #ORM\Column(name="avg_score", type="integer")
*/
private $avgScore;
/**
* #ORM\OneToMany(targetEntity="Session", mappedBy="service")
*/
private $sessionList;
}
class Session{
/**
* #ORM\ManyToOne(targetEntity="Service", inversedBy="sessionList")
* #ORM\JoinColumn(name="service_id", referencedColumnName="id")
*/
private $service;
/**
* #var int
*
* #ORM\Column(name="score", type="integer", nullable=true)
*/
private $score;
}
With Doctrine QueryBuilder how can I update $avgScore of Service entity everytime new Session with $score is created?
This is what I tried to do:
$qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder();
$q = $qb->update('AppBundle:Service', 's')
->join('AppBundle:Session', 'ss')
->addSelect('avg(ss.score) as score_avg')
->groupBy('ss.service')
->set('s.avgScore', 'score_avg')
->where('s.id = ?1')
->setParameter(1, $service->getId())
->getQuery();
$q->execute();
You need to create a Doctrine Events Listener
services:
my.listener:
class: AppBundle\EventListener\AvgScoreUpdater
tags:
- { name: doctrine.event_listener, event: prePersist }
And then in AvgScoreUpdater implement logic:
class AvgScoreUpdater
{
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!($entity instanceof Session) || !$entity->getScore()) {
return;
}
$entityManager = $args->getEntityManager();
$service = $entity->getService();
// Then realize logic to update avg_score on a service
}
}

Mapping Entity in CouchDb Symfony2

I'm using couchDb in symfony 2.7.2.
I have several doubts.
Now I installed this Bundle
And I create one entity for testing
<?php
namespace foo\GarageBundle\Document;
use Doctrine\ODM\CouchDB\Mapping\Annotations as CouchDB;
/**
* #CouchDB\Document
*/
class Utente
{
/** #CouchDB\Id */
private $id;
/** #CouchDB\Field(type="string") */
private $nome;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nome
*
* #param string $nome
* #return Utente
*/
public function setNome($nome)
{
$this->nome = $nome;
return $this;
}
/**
* Get nome
*
* #return string
*/
public function getNome()
{
return $this->nome;
}
}
In my controller I added this Code
$dm = $this->container->get('doctrine_couchdb.client.default_connection');
$doc = $this->container->get('doctrine_couchdb.odm.default_document_manager');
try{
$dm->createDatabase($dm->getDatabase());
}catch(\Exception $e){
$msg = $e->getMessage();
}
$user = new Utente();
$user->setNome('foo');
$doc->persist($user);
$doc->flush();
my config.yml is
doctrine_couch_db:
client:
default_connection: default
connections:
default:
dbname: symfony2
odm:
default_document_manager: default
document_managers:
default:
auto_mapping: true
With controller I created Database but I can't insert the new Document, I got this error
The class 'foo\GarageBundle\Document\Utente' was not found in the chain configured namespaces
And I don't understand why it is useful to use a bundle as what I am using ( I know it could be a stupid question ), and why I have to use * #CouchDB\Document instead of #Document inside my entity ?
Seems a problem related the namespace of the entity class.
The automapping is registering the CouchDocument subnamespace of
your bundle, not Document (which is auto-mapped by
DoctrineMongoDBBundle)
So use a different namespace for the User class and the other Counch you use, as follow:
namespace foo\GarageBundle\CouchDocument;
In particular:
<?php
namespace foo\GarageBundle\CouchDocument;
use Doctrine\ODM\CouchDB\Mapping\Annotations as CouchDB;
/**
* #CouchDB\Document
*/
class Utente
{
Hope this help
See this discussion on github.
/**
* #CouchDB\Document
* #CouchDB\Index
*/
class Utente
{

Symfony2 cannot find my doctrine2 entity class in the controller - how to fix?

I'm trying to run a simple SQL statement (something like select * from table) in my Symfony2 controller but it's not working. Somehow Symfony cannot find the class.
some info:
I've tried providing the full namespace + class name and just class name in the FROM clause
I've tried DQL and QueryBuilder (see code below. option1 and option2)
AppKernel is loading my DoctrineBundle. This was already there when I use composer to create my project
I've tried auto_mapping true and false in settings.yml
snippets of my codes are below
error message:
[Semantical Error] line 0, col 14 near 'Job j ORDER BY': Error: Class 'Job' is not defined.
500 Internal Server Error - QueryException
1 linked Exception:
QueryException ยป
[2/2] QueryException: [Semantical Error] line 0, col 14 near 'Job j ORDER BY': Error: Class 'Job' is not defined. +
[1/2] QueryException: SELECT u FROM Job j ORDER BY j.name ASC +
settings.yml
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver, add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
#auto_mapping: false
#mappings:
# MyAppMyBundle:
# type: annotation
# dir: Entity/
my controller
<?php
// src/MyApp/MyBundle/Controller/JobsController.php
namespace MyApp\MyBundle\Controller;
use MyApp\MyBundle\Entity\Job;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class JobsController extends Controller {
public function listAction() {
$em = $this->getDoctrine()->getEntityManager();
//$qb = $em->createQueryBuilder();
//option1
//$qb ->select("j")
// ->from("Job", "j")
// ->orderBy("j.name", "ASC");*/
//return $this->render('MyBundle:Jobs:list.html.twig', array('jobs' => $qb->getQuery()->getResult()));
//option2
$qb = $em->createQuery("SELECT u FROM Job j ORDER BY j.name ASC");
return $this->render('MyBundle:Jobs:list.html.twig', array('jobs' => $qb->getResult()));
}
}
my entity class
<?php
// src/MyApp/MyBundle/Entity/Job.php
namespace MyApp\MyBundle\Entity;
use Doctrine\ORM\Mapping;
/**
* #Mapping\Entity
* #Mapping\Table(name="jobs")
*/
class Job {
/**
* #Mapping\Column(name="job_id", type="integer")
* #Mapping\Id
* #Mapping\GeneratedValue(strategy="AUTO")
*/
protected $jobId;
/**
* #Mapping\Column(name="name", type="text")
*/
protected $name;
/**
* #Mapping\Column(name="job_desc", type="text")
*/
protected $description;
/**
* #Mapping\Column(name="personal_req", type="text")
*/
protected $requirements;
/**
* Get jobid
*
* #return integer
*/
public function getJobId() {
return $this->applicationId;
}
/**
* Set name
*
* #param \text $name
* #return Job
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return text
*/
public function getName() {
return $this->name;
}
/**
* Set description
*
* #param \text $description
* #return Job
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return text
*/
public function getDescription() {
return $this->description;
}
/**
* Set requirements
*
* #param \text $requirements
* #return Job
*/
public function setRequirements($requirements) {
$this->requirements = $requirements;
return $this;
}
/**
* Get requirements
*
* #return text
*/
public function getRequirements() {
return $this->requirements;
}
}
use the full namespace if you make a query directly with entitymanager or just MyAppMyBundle:Job
be sure that your bundle is present in AppKernel
prefer to use $em->getRepository('MyAppMyBundle:Job')->createQueryBuilder('j') or $em->getRepository('MyAppMyBundle:Job')->findBy(array(),array('name' => 'ASC')
validate your model with php app/console doctrine:mapping:info and php app/console doctrine:schema:validate
Exceptions in symfony are always perfect so keep the focus on what your exception says
verify namespace of entity class. Because no generate error when write wrong namespace, but no find entity

Categories