I've followed every step in the book, but I can't get to work any entity custom repository.
The problem her is that i have been trying to call the method filtrerExperienceTotal but The code completion shortcut (Ctrl-Space) can't find the method, please help
For example, I have my User entity:
<?php
namespace MTO\CrowdRiseBundle\Controller;
use MTO\CrowdRiseBundle\Entity\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use MTO\CrowdRiseBundle\Entity\User;
class ProfilsController extends Controller
{
public function filtrerExperienceTotal(){
$em = $this->getDoctrine()->getManager();
$req = $this->get('request');
if ($req->getMethod() == 'POST') {
$rechexperienceTot = $req->get('rechexperienceTotname');
$Users = $em->getRepository('MTOCrowdRiseBundle:User')->filtrerExperienceTotal(0,99);
if (!($Users == null)) {
return $this->render('MTOCrowdRiseBundle:Profils:profils.html.twig', array('users' => $Users));
} else {
return $this->render('MTOCrowdRiseBundle:Profils:profils.html.twig', array('users' => NUll));
}
}
return ($this->redirectToRoute('mto_crowd_rise_profils'));
}
and the repository class
class UserRepository extends EntityRepository
{
public function chercherNom($nom){
$qb = $this->getEntityManager()->createQueryBuilder('p')
->where('p.nom LIKE :nom')
->orWhere('p.prenom LIKE :nom')
->orWhere('p.username LIKE :nom')
->setParameter('nom', $nom)
->getQuery()->getResult();
return $qb;
}
public function filtrerExperienceTotal($experiencemin,$experiencemax){
$qb = $this->getEntityManager()->createQueryBuilder('p')
->select('p ')
->where('p.experienceTot between :parm1 and :param2')
->setParameter('param1', $experiencemin)
->setParameter('param2', $experiencemax)
->getQuery()->getResult();
return $qb;
}
}
final the user.orm.yml
MTO\CrowdRiseBundle\Entity\User:
type: entity
table: user
repositoryClass: MTO\CrowdRiseBundle\Entity\UserRepository
id:
id:
type: integer
nullable: false
unsigned: false
comment: ''
id: true
generator:
strategy: IDENTITY
fields:
nom:
type: string
nullable: false
length: 40
fixed: false
comment: ''
prenom:
type: string
nullable: false
length: 40
fixed: false
comment: ''
datenaissance:
type: date
nullable: false
comment: ''
column: dateNaissance
situationprof:
type: string
nullable: false
length: null
fixed: false
comment: ''
column: situationProf
secteur:
type: string
nullable: false
length: null
fixed: false
comment: ''
experiencetot:
type: integer
nullable: false
unsigned: false
comment: ''
column: experienceTot
solde:
type: integer
nullable: false
unsigned: false
comment: ''
column: solde
paysnatal:
type: string
nullable: false
length: 40
fixed: false
comment: ''
column: paysNatal
image:
type: text
nullable: false
length: null
fixed: false
comment: ''
role:
type: string
nullable: false
length: null
fixed: false
comment: ''
etat:
type: string
nullable: false
length: null
fixed: false
comment: ''
sexe:
type: string
nullable: false
length: null
fixed: false
comment: ''
lifecycleCallbacks: { }
please guys i do really need a help
Well at the end, the probleme was from the IDE, all i need it is to force it and write manually the name of the method, it work fine, Thanks alot
Related
I'm trying to create a OneToOne relationship between two tables using YAML. I'm not sure how they are supposed to communicate.
class Games
{
private $id;
private $title;
private $description;
private $img_link;
private $website_link;
private $pegi;
private $release_date;
private $requirements;
}
App\Entity\Games:
type: entity
repositoryClass: App\Repository\GamesRepository
table: games
id:
id:
type: integer
generator:
strategy: AUTO
fields:
title:
type: string
length: 255
nullable: true
description:
type: text
nullable: true
img_link:
type: text
nullable: true
website_link:
type: text
nullable: true
pegi:
type: integer
nullable: true
release_date:
type: date
nullable: true
OneToOne:
requirements:
targetEntity: App\Entity\Requirements
joinColumn:
name: requirements_fk
referencedColumnName: id
class Requirements
{
private $id;
private $os_min;
private $cpu_min;
private $ram_min;
private $hdd_min;
private $gpu_min;
private $directx_min;
private $os_req;
private $cpu_req;
private $ram_req;
private $hdd_req;
private $gpu_req;
private $directx_req;
}
App\Entity\Requirements:
type: entity
repositoryClass: App\Repository\RequirementsRepository
table: requirements
id:
id:
type: integer
generator:
strategy: AUTO
fields:
os_min:
type: string
length: 255
nullable: true
cpu_min:
type: string
length: 255
nullable: true
ram_min:
type: integer
nullable: true
hdd_min:
type: integer
nullable: true
gpu_min:
type: string
lenght: 255
nullable: true
directx_min:
type: integer
nullable: true
os_req:
type: string
length: 255
nullable: true
cpu_req:
type: string
length: 255
nullable: true
ram_req:
type: integer
nullable: true
hdd_req:
type: integer
nullable: true
gpu_req:
type: string
lenght: 255
nullable: true
directx_req:
type: integer
nullable: true
I try querying it like this, but it always returns null even though it should return an entry.
$temp = $this->getDoctrine()->getRepository(Games::class)->find($id);
$requirements = $temp->getRequirements();
I don't get any errors so, it's really hard to try and debug it. Acording to documentation it looks okay. So, not sure where the problem is.
If class Games is your entity you should have the method getRequirements() in there.
Try to generate the entities based on the schema if your entities are empty.
https://symfony.com/doc/current/doctrine/reverse_engineering.html
The key problem is that OneToOne != oneToOne in YAML.
I use easyadmin, I wish for the field "role" display the choice of roles in a field type "radio" but an error (array to string conversion) of this type occurs (see image below):
Notice: Array to string conversion
here is my config:
easy_admin:
entities:
User:
class: AppBundle\Entity\User
form:
fields:
- { property: 'username' }
- { property: 'email' }
- { property: 'enabled' }
- property: 'plainPassword'
type: 'repeated'
type_options:
type: Symfony\Component\Form\Extension\Core\Type\PasswordType
required: false
first_options: { label: '%label.password%' }
second_options: { label: '%label.password_confirmation%' }
invalid_message: fos_user.password.mismatch
- property: 'roles'
type: 'choice'
type_options:
mapped: true
expanded: true
multiple: false
choices: { 'Conseiller': 'ROLE_USER', 'Administrateur': 'ROLE_ADMIN' }
Someone would have a solution to offer me so that I can display radio buttons with easyadmin?
thanks in advance
#johan-rm what you did was almost correct.
In fact you can't use radio buttons for roles because roles (see the s) is multiple choice field. You need to use check boxes (or a mulitple select).
In your code, the only thing that was wrong was this part: multiple: false.
If you try to map an array to a single choice field, you are trying to map an array to a string, hence the error.
Just change multiple: false to multiple: true.
This is the result:
easy_admin:
entities:
User:
class: AppBundle\Entity\User
form:
fields:
- { property: 'username' }
- { property: 'email' }
- { property: 'enabled' }
- property: 'plainPassword'
type: 'repeated'
type_options:
type: Symfony\Component\Form\Extension\Core\Type\PasswordType
required: false
first_options: { label: '%label.password%' }
second_options: { label: '%label.password_confirmation%' }
invalid_message: fos_user.password.mismatch
- property: 'roles'
type: 'choice'
type_options:
mapped: true
expanded: true
multiple: true
choices: { 'Conseiller': 'ROLE_USER', 'Administrateur': 'ROLE_ADMIN' }
Here's a solution in Symfony 3.4 to this (uses Yes/No dropdown) that might help:
in config.yml
imports:
...
- { resource: easyAdmin.yml }
in easyadmin.yml
fields:
...
- property: 'hasRoleAdmin'
label: 'Is admin?'
type: choice
type_options:
choices:
'No': 'No'
'Yes': 'Yes'
in User entity:
public function hasRoleAdmin()
{
return ($this->hasRole('ROLE_ADMIN')) ? 'Yes' : 'No';
}
public function setHasRoleAdmin($isAdmin)
{
if ('Yes' === $isAdmin && 'No' === $this->hasRole('ROLE_ADMIN')) {
$this->addRole('ROLE_ADMIN');
}
if ('No' === $isAdmin && 'Yes' == $this->hasRole('ROLE_ADMIN')) {
$this->removeRole('ROLE_ADMIN');
}
$this->isAdmin = $isAdmin;
}
I have two Entities Company and Storage with One-To-Many Bidirectional relationship. Entities and their relations are cached (doctrine second level cache). The issue is that, when i create a new Storage entity, Company storages collection doesn't have this new entity until I clear the cache manually.
AppBundle\Entity\Main\Company:
type: entity
table: main.company
cache:
usage: NONSTRICT_READ_WRITE
id:
id:
type: integer
nullable: false
id: true
generator:
strategy: IDENTITY
fields:
legalName:
type: string
nullable: false
length: 255
options:
fixed: false
column: legal_name
oneToMany:
storages:
targetEntity: AppBundle\Entity\Main\Storage
mappedBy: company
cascade: ["all"]
orphanRemoval: true
cache:
usage: NONSTRICT_READ_WRITE
AppBundle\Entity\Main\Storage:
type: entity
table: main.storage
cache:
usage: NONSTRICT_READ_WRITE
id:
id:
type: integer
nullable: false
options:
unsigned: false
id: true
generator:
strategy: IDENTITY
fields:
storageName:
type: string
nullable: true
length: 255
options:
fixed: false
column: storage_name
manyToOne:
company:
targetEntity: AppBundle\Entity\Main\Company
cascade: ["all"]
fetch: LAZY
mappedBy: null
inversedBy: storages
joinColumns:
company_id:
referencedColumnName: id
orphanRemoval: false
cache:
usage: NONSTRICT_READ_WRITE
This is action where Storage is created. There is nothing unusual.
public function addAction(Request $request)
{
$form = $this->createForm(StorageAddType::class, null);
$form->handleRequest($request);
if (!$form->isSubmitted()) {
throw new \RuntimeException('Некорректный запрос');
}
if (!$form->isValid()) {
throw new \Symfony\Component\Validator\Exception\ValidatorException((string)$form->getErrors(true));
}
$doctrine = $this->getDoctrine();
/**
* #var Storage $storage
*/
$storage = $form->getData();
$manager = $doctrine->getManager();
$manager->persist($storage);
$manager->flush();
return $this->createAjaxDataResponse($this->createSuccessMessage('Storage successfully added'));
}
Such behavior is watched only when i try to create new Entity (Storage). Then on update/delete actions - Storages collection of Company are updated.
You are clearly wrong with persisting data. You try to persist unserialized object from form into uknown repository via manager.
Try this:
public function addAction(Request $request)
{
$form = $this->createForm(StorageAddType::class, null);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if($form->isSubmitted() && $form->isValid())
{
$storage = new Storage();
$storage->setVal1($form->get('Val1'));
$storage->setVal2($form->get('Val2'));
$em->persist($storage);
$em->flush();
return $this->createAjaxDataResponse($this->createSuccessMessage('Storage successfully added'));
}
return $this->render('YOUR_TWIG_LAYOUT', [
'form' => $form->createView()
]);
}
You can also try to persist whole object, if form is seriaized properly by serializing data into entity. Write method like setValsFromForm($data) and serialize vars from $data form.
Then change these lines:
$storage->setVal1($form->get('Val1'));
$storage->setVal2($form->get('Val2'));
into
$storage->setValsFromForm($form->getData());
Also:
Exceptions and form validations should be handled by Form Validator in form class, not in controller. Exception is when you create form via formbuilderinterface in the controller, but you add logic there, not outside $form class.
I am working with a bundle called rss-atom-bundle. Through this bundle I should be able to fetch the RSS feeds and save them to the database.
I can get the bundle to work up till getting the feeds from the URL but when I try to presist I get the following error and I just cant figure it out why I am getting it.
The class 'Debril\RssAtomBundle\Protocol\Parser\Item' was not found in the chain configured namespaces Symfony\Bundle\AsseticBundle\Entity, AppBundle\Entity`
Looking online and at stackoverflow i came across questions that were related to this but all of them are talking about by default the Entity should be inside the Entity folder of the Bundle and if they are not then this error appears but my Entity files are inside Entity folder and I followed the instructions given by the bundle author but still i cant get passed this error
This is what my Controller looks like
$em = $this->getDoctrine()->getManager();
// fetch the FeedReader
$reader = $this->container->get('debril.reader');
// this date is used to fetch only the latest items
$unmodifiedSince = '01/01/2000';
$date = new \DateTime($unmodifiedSince);
// the feed you want to read
$url = 'http://example.com/feed/';
$feeds = $reader->getFeedContent($url, $date);
$items = $feeds->getItems();
dump($items);
foreach ( $items as $item ) {
$em->persist($item);
}
$em->flush();
As per bundle instructions I did implement FeedInterface to my Feed Entity and ItemInInterface, ItemOutInterface to my Item Entity
This is what my orm.yml looks like for Feed and Item Entity
Feed
AppBundle\Entity\Feed:
type: entity
table: null
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
title:
type: string
length: 255
description:
type: text
link:
type: text
publicId:
type: text
lastModified:
type: datetime
lastViewed:
type: datetime
oneToMany:
items:
targetEntity: AppBundle\Entity\Item
mappedBy: feed
cascade: ["persist"]
lifecycleCallbacks: { }
Item
AppBundle\Entity\Item:
type: entity
table: null
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
title:
type: string
length: 255
title:
type: text
nullable: true
summary:
type: text
nullable: true
description:
type: text
nullable: true
medias:
type: text
nullable: true
updated:
type: string
nullable: true
publicId:
type: string
nullable: true
link:
type: string
nullable: true
comment:
type: string
nullable: true
author:
type: string
nullable: true
manyToOne:
feed:
targetEntity: AppBundle\Entity\Feed
inversedBy: items
joinColumn:
name: feed_id
referencedColumnName: id
Any help will be really appreciated as I am clueless why i am getting the error?
Try to add RssAtomBundle to the list with mappings in app/config/config.yml
orm:
entity_managers:
default:
connection: default
mappings:
AppBundle: ~
AsseticBundle: ~
RssAtomBundle: ~
When running:
php app/console doctrine:schema:validate
I receive the error:
[Mapping] FAIL - The entity-class 'Path\ToBundle\Entity\Variant' mapping is invalid:
* The referenced column name 'localsku' has to be a primary key column on the target entity class 'Path\ToBundle\Entity\Inventory'.
The killer here is that 'localsku' is indeed a primary key. Am I missing something major here?
Thanks in advance for any assistance, and I apologize if I've missed some key piece of information.
Variant Entity is defined as:
Path\ToBundle\Entity\Variant:
type: entity
table: variant
uniqueConstraints:
sku:
columns:
- sku
id:
variantId:
type: integer
nullable: false
unsigned: false
comment: ''
id: true
column: variant_id
generator:
strategy: IDENTITY
fields:
name:
type: string
nullable: false
length: 255
fixed: false
comment: ''
sku:
type: string
nullable: false
length: 255
fixed: false
comment: ''
oneToOne:
inventory:
targetEntity: Inventory
cascade: { }
mappedBy: null
inversedBy: variant
joinColumns:
sku:
referencedColumnName: localsku
orphanRemoval: false
lifecycleCallbacks: { }
Inventory Entity is defined as:
Path\ToBundle\Entity\Inventory:
type: entity
table: Inventory
id:
localsku:
type: string
nullable: false
length: 255
fixed: false
comment: ''
id: true
column: LocalSKU
generator:
strategy: IDENTITY
fields:
itemname:
type: string
nullable: true
length: 255
fixed: false
comment: ''
column: ItemName
qoh:
type: integer
nullable: true
unsigned: false
comment: ''
column: QOH
location:
type: string
nullable: true
length: 250
fixed: false
comment: ''
column: Location
barcode:
type: string
nullable: true
length: 25
fixed: true
comment: ''
column: Barcode
oneToOne:
variant:
targetEntity: Variant
cascade: { }
mappedBy: inventory
inversedBy: null
joinColumns:
localsku:
referencedColumnName: sku
orphanRemoval: false
lifecycleCallbacks: { }
Variant Entity reference to Inventory:
/**
* Inventory
*
* #var \Path\ToBundle\Entity\Inventory
*
* #ORM\OneToOne(targetEntity="Path\ToBundle\Entity\Inventory", inversedBy="variant")
* #ORM\JoinColumn(name="sku", referencedColumnName="localsku")
*/
protected $inventory;
Inventory Entity reference to Variant:
/**
* Variant
*
* #var \Path\ToBundle\Entity\Variant
*
* #ORM\OneToOne(targetEntity="Path\ToBundle\Entity\Variant", inversedBy="inventory")
* #ORM\JoinColumn(name="localsku", referencedColumnName="sku")
*/
protected $variant;
Your association mapping is wrong.
It should be something like that, assuming Variant table have a "sku" field.
Variant Entity :
/**
* Inventory
*
* #var \Path\ToBundle\Entity\Inventory
*
* #ORM\OneToOne(targetEntity="Path\ToBundle\Entity\Inventory", inversedBy="variant")
* #ORM\JoinColumn(name="sku", referencedColumnName="localsku")
*/
protected $inventory;
Inventory Entity :
/**
* Variant
*
* #var \Path\ToBundle\Entity\Variant
*
* #ORM\OneToOne(targetEntity="Path\ToBundle\Entity\Variant", mappedBy="inventory")
*/
protected $variant;
http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#one-to-one-bidirectional
P.S : I'm curious. You are using both yml configuration and annotation for the same entities ? I'm not sure that doctrine is able to merge them, does it works ?