No entity manager defined for class - php

I am trying to just display a list. My Supplier and Property list were displaying until I implemented the product list :(
Now I get this error with the Supplier and Property lists but not for the newly added product list:
Here is my app/config.yml:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
parameters:
sylius.locale: "%locale%"
framework:
#esi: ~
translator: { fallbacks: ["%locale%"] }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
storage_id: session.storage.php_bridge
# handler_id set to null will use default session handler from php.ini
handler_id: ~
fragments: ~
http_method_override: true
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
form:
resources:
- 'SonataCoreBundle:Form:datepicker.html.twig'
# Assetic Configuration
assetic:
debug: "%kernel.debug%"
use_controller: false
#java: /usr/bin/java
node: /usr/bin/node
node_paths: [ /usr/lib/node_modules, %kernel.root_dir%/../node_modules ]
filters:
autoprefixer:
bin: %kernel.root_dir%/../node_modules/autoprefixer/autoprefixer
cssrewrite: ~
less:
apply_to: "\.less$"
bin: %kernel.root_dir%/../node_modules/less
uglifycss:
bin: %kernel.root_dir%/../node_modules/uglifycss
uglifyjs:
bin: %kernel.root_dir%/../node_modules/uglifyjs
#closure:
# jar: "%kernel.root_dir%/Resources/java/compiler.jar"
#yui_css:
# jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar"
# Doctrine Configuration
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
mapping_types:
enum: string
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
default:
connection: default
auto_mapping: true
dql:
string_functions:
HS_CONCAT_ADDRESS: AppBundle\DQL\HSConcatAddress
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
# FOS UserBundle Configuration
fos_user:
registration:
form:
type: hs_user_registration
db_driver: orm
firewall_name: main
user_class: AppBundle\Entity\User
service:
user_manager: app.security.user_manager
# Doctrine migration bundle Configuration
doctrine_migrations:
dir_name: %kernel.root_dir%/DoctrineMigrations
namespace: Application\Migrations
table_name: migration_versions
name: Application Migrations
# Sonata Admin Configuration
sonata_admin:
options:
use_select2: false # disable select2
title: App
title_logo: bundles/sonataadmin/logo_title.png
# Override default template
templates:
show: AppBundle:Admin/Backend:show.html.twig
edit: AppBundle:Admin/Backend:edit.html.twig
layout: AppBundle:Common/Admin:standard_layout.html.twig
security:
# handler: sonata.admin.security.handler.role
#sonata_intl:
# timezone:
# locales:
# en_GB: Europe/London
# default: Europe/London
# Sonata Block Configuration
sonata_block:
default_contexts: [cms]
blocks:
sonata.user.block.menu: # used to display the menu in profile pages
sonata.user.block.account: # used to display menu option (login option)
sonata.admin.block.admin_list:
contexts: [admin]
sonata.admin.block.search_result:
contexts: [admin]
knp_menu:
# use "twig: false" to disable the Twig extension and the TwigRenderer
twig:
template: knp_menu.html.twig
# if true, enables the helper for PHP templates
templating: false
# the renderer to use, list is also available by default
default_renderer: twig
# STOF Doctrine Extensions Configuration
stof_doctrine_extensions:
default_locale: %locale%
orm:
default:
translatable: true
sluggable: true
timestampable: true
a2lix_translation_form:
locale_provider: default # [1]
locales: ["%locale%"] # [1-a]
default_locale: "%locale%" # [1-b]
manager_registry: doctrine # [2]
# Sylius Archetype
sylius_archetype:
classes:
product:
subject: Sylius\Component\Product\Model\Product
attribute: Sylius\Component\Product\Model\Attribute
option: Sylius\Component\Product\Model\Option
archetype:
model: Sylius\Component\Product\Model\Archetype
repository: Sylius\Bundle\ResourceBundle\Doctrine\ORM\TranslatableEntityRepository
translatable:
targetEntity: Sylius\Component\Product\Model\ArchetypeTranslation
archetype_translation:
model: Sylius\Component\Product\Model\ArchetypeTranslation
sylius_product:
driver: doctrine/orm
classes:
product:
model: AppBundle\Entity\Product
controller: AppBundle\Controller\Backend\ProductController
form:
default: AppBundle\Form\Type\ProductType
translatable:
targetEntity: AppBundle\Entity\ProductTranslation
product_translation:
model: AppBundle\Entity\ProductTranslation
form:
default: AppBundle\Form\Type\ProductTranslationType
#sylius_resource:
# resources:
# app.backend:
# driver: doctrine/orm
# object_manager: default
# classes:
# controller: AppBundle\Controller\Backend\ResourceController
# model: AppBundle\Entity\Product
# Sylius Attribute
sylius_attribute:
driver: doctrine/orm
# Sylius Locale
sylius_locale:
driver: doctrine/orm
# Sylius Translation
sylius_translation:
default_mapping:
translatable:
field: translations
currentLocale: currentLocale
fallbackLocale: fallbackLocale
translation:
field: translatable
locale: locale
# Sylius Variation
sylius_variation:
driver: doctrine/orm
classes:
product:
variant:
model: AppBundle\Entity\ProductVariant
form: AppBundle\Form\Type\ProductVariantType
My admin class:
namespace AppBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Symfony\Component\EventDispatcher\Event;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Form\Type;
use Sonata\AdminBundle\Validator\ErrorElement;
use AppBundle\Entity\Suppliers as Suppliers;
use AppBundle\Form\Type\CreateSupplierForm;
use Symfony\Component\DependencyInjection\ContainerInterface;
class SupplierAdmin extends Admin
{
/**
* {#inheritdoc}
*/
protected $baseRouteName = 'Admin\SupplierAdmin';
/**
* {#inheritdoc}
*/
protected $baseRoutePattern = 'supplier';
/**
* #var ContainerInterface
*/
private $container;
public function setContainer (ContainerInterface $container)
{
$this->container = $container;
}
/**
* #param \Sonata\AdminBundle\Show\ShowMapper $showMapper
*
* #return void
*/
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->with('Supplier Details')
->add('id')
->add('name')
->add('created')
->end();
if ($this->getSubject()->getType() == 'LPE') {
$showMapper->with('Property Expert')
->add('LpeFirstName', null, array('label' => 'First Name'))
->add('LpeLastName', null, array('label' => 'Last Name'))
->add('LpeEmail', null, array('label' => 'Email'))
->add('ContractType', null, array('label' => 'Type'))
->add('regions', 'entity', array(
'class' => 'AppBundle:Regions',
"multiple" => true,
'label' => 'Regions Covered'
))
->end();
}
}
/**
* #param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
*
* #return void
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
->add('Type')
->addIdentifier('name')
->add('created', 'date', array(
'pattern' => 'dd/MM/Y # H:m',
'locale' => 'en_GB',
'timezone' => 'Europe/London',
))
// add custom action links
->add('_action', 'actions', array(
'actions' => array(
'show' => array(),
'delete' => array()
)
));
}
/**
* #param \Sonata\AdminBundle\Datagrid\DatagridMapper $datagridMapper
*
* #return void
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('type', null, array(),
'choice',
array('choices' => Suppliers::getTypes()))
->add('name');
}
protected function configureRoutes(RouteCollection $collection)
{
parent::configureRoutes($collection);
$collection->add('create', 'create', array(
'_controller' => 'AppBundle:Backend/SupplierAdmin:createSupplier'
)
);
$collection->add('show', $this->getRouterIdParameter() . '/show', array(
'_controller' => 'AppBundle:Backend/SupplierAdmin:show',
)
);
$collection->add('delete', $this->getRouterIdParameter() . '/delete', array(
'_controller' => 'AppBundle:Backend/SupplierAdmin:delete',
)
);
}
/**
* #return array
*/
public function getBatchActions()
{
// Disable all batch actions for now
$actions = array();
return $actions;
}
/**
* {#inheritdoc}
*/
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
// Default Alias is "o"
$query->orderBy('o.id', 'DESC');
$query->setSortOrder('DESC');
return $query;
}
public function preUpdate($supplier)
{
$supplier->setDeleted(0);
return $supplier;
}
public function preCreate($supplier)
{
$supplier->setDeleted(0);
return $supplier;
}
}
And lastly my Supplier entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Suppliers
*
* #ORM\Table(
* name="suppliers",
* indexes={
* #ORM\Index(
* name="supplier_name", columns={"name"}
* )
* })
* #ORM\Entity
* #ORM\HasLifecycleCallbacks()
*/
class Suppliers
{
const TYPE_INTERNAL = 'internal';
const TYPE_EXTERNAL = 'external';
const TYPE_LPE = 'lpe';
protected static $types = array(
self::TYPE_INTERNAL => 'Internal',
self::TYPE_EXTERNAL => 'External',
self::TYPE_LPE => 'LPE'
);
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false, options={"unsigned":true})
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #Assert\NotNull()
* #ORM\Column(name="type", type="string", nullable=false, options={"default":"lpe"})
*/
private $type;
/**
* #var string
*
* #Assert\NotNull()
* #ORM\Column(name="name", type="string", nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #var string
*
* #ORM\Column(name="updated", nullable=true, type="datetime")
*/
private $updated;
/**
* #var string
*
* #ORM\Column(name="deleted", type="boolean", options={"default":0})
*/
private $deleted;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Regions")
* #ORM\JoinTable(name="supplier_regions",
* joinColumns={
* #ORM\JoinColumn(
* name="supplier_id",
* referencedColumnName="id"
* )
* },
* inverseJoinColumns={
* #ORM\JoinColumn(
* name="region_id",
* referencedColumnName="postcode"
* )
* }
* )
*/
private $regions;
private $lpe;
public function __construct()
{
$this->regions = new ArrayCollection();
}
public function getRegions()
{
return $this->regions;
}
public function setRegions($regions)
{
$this->regions = $regions;
return $this;
}
public function getLpe()
{
return $this->lpe;
}
public function setLpe($lpe)
{
$this->lpe = $lpe;
return $this;
}
/**
* #return string
*/
public function getLpeFirstName()
{
return $this->lpe->getUser()->getFirstName();
}
/**
* #return string
*/
public function getLpeLastName()
{
return $this->lpe->getUser()->getLastName();
}
/**
* #return string
*/
public function getLpeEmail()
{
return $this->lpe->getUser()->getEmail();
}
public function getContractType()
{
return $this->lpe->getContractType();
}
public function getUser()
{
return $this->lpe->getUser();
}
public function setUser($user)
{
$this->lpe->setUser($user);
return $this;
}
public function setFirstName($name)
{
$this->user->setFirstName($name);
return $this;
}
public function getFirstName()
{
return $this->user->getFirstName();
}
public function setLastName($name)
{
$this->user->setLastName($name);
return $this;
}
public function getLastName()
{
return $this->getUser()->getLastName();
}
public function setEmail($email)
{
$this->getUser()->setEmail($email);
return $this;
}
public function getEmail()
{
return $this->getUser()->getEmail();
}
/**
* #var string
*/
private $entityName;
/**
* Get id
*
* #return integer
*/
public function nullId()
{
return $this->id =null;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = strtolower($type);
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
if ($this->type == 'lpe') {
return strtoupper($this->type);
}
return ucwords($this->type);
}
/**
* Set name
*
* #param string $name
* #return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set created
*
* #param string $created
* #return $this
*/
public function setCreated($created)
{
if (!empty($created)) {
$this->created = $created;
} else {
$this->created = new \DateTime("now");
}
return $this;
}
/**
* Get created
*
* #return string
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param string $updated
* #return User
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return string
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return User
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* #ORM\PrePersist()
*/
public function onPrePersist()
{
$this->created = new \DateTime();
$this->updated = new \DateTime();
if ($this->deleted === null) {
$this->deleted = 0;
}
if ($this->type === null) {
$this->type = 'lpe';
}
if ($this->name === null) {
$this->name = '';
}
}
/**
* #ORM\PreUpdate()
*/
public function onPreUpdate()
{
$this->created = new \DateTime();
$this->updated = new \DateTime();
if ($this->deleted === null) {
$this->deleted = 0;
}
}
/**
* #return array
*/
public static function getTypes()
{
return self::$types;
}
/**
* Set entityName
*
* #param string $name
* #return User
*/
public function setEntityName($name)
{
$this->entityName = $name;
return $this;
}
public function __toString()
{
if ($this->getUser() === null) {
return 'Supplier' . ($this->id !== null ? ' #' . $this->id.'' : '' );
}
return (string) ($this->id !== null ? '#' . $this->id.' ' : '' ) . $this->getUser()->getEmail();
}
}
Any suggestions? :)

I think it is in your configuration file
doctrine:
[...]
orm:
[...]
mappings:
AppBundle:
type: ~
dir: "Entity"
prefix: "AppBundle\Entity"
is_bundle: ~
If it is not working, look over your namespaces, I think (but not sure) it should be like PROJECT\BUNDLE\Entity and not just BUNDLE\Entity (for both namespace and use statements)

You have to set your doctrine configuration to add your bundle to the ORM :
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
orm:
auto_generate_proxy_classes: '%kernel.debug%'
entity_managers:
default:
mappings:
ApplicationSonataUserBundle: ~
SonataUserBundle: ~
FOSUserBundle: ~
**YourBundleNameBundle**: ~

Related

Symfony 3 - How to authenticate a user from a password encrypted by bcrypt?

I have a User entity, with password encryption by bcrypt, in the database.
In fact, when a user is created, I generate a random password of 7 characters, and send him by mail. This password is encrypted using bcrypt and then in the database in the password attribute.
I would like that when my user connects from my login form, he can enter the password that I sent him by email to authenticate. But I do not understand how to do it. I can look at different sites, I do not see.
In addition, I think my code is a little mess ... My ultimate goal being to authenticate the user, so he has an open session, with a possibility to disconnect, and it is restricted to certain pages. But also to manage if the user is activated, and its expiration date.
I emphasize the fact that I am a beginner in symfony (I discovered it 2 weeks ago as part of my internship, and I knew very little PHP, so it's quite difficult for me)
I do not use the fosUserBundle bundle.
This is my code :
User.php :
<?php
namespace Site\PagesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="Site\PagesBundle\Repository\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, nullable=true, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="prenom", type="string", length=255)
*/
private $prenom;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=254, unique=true)
*/
private $email;
/**
* #Assert\Length(max=4096)
*/
private $plainPassword;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=64, nullable=true)
*/
private $password;
/**
* #var int
*
* #ORM\Column(name="nbTelechargementsAuto", type="integer", nullable=true)
*/
private $nbTelechargementsAuto;
/**
* #var bool
*
* #ORM\Column(name="isActif", type="boolean")
*/
private $isActif=0;
/**
* #ORM\Column(type="datetime", nullable=true)
*
* #var \DateTime
*/
private $createdAt;
/**
* #var bool
*
* #ORM\Column(name="isCreated", type="boolean")
*/
private $isCreated=0;
/**
* #ORM\Column(type="array")
*/
private $roles;
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return User
*/
public function setCreatedAt()
{
$this->createdAt = new \DateTimeImmutable();
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
*
* #return User
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set nom
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set prenom
*
* #param string $prenom
*
* #return User
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set nbTelechargementsAuto
*
* #param integer $nbTelechargementsAuto
*
* #return User
*/
public function setNbTelechargementsAuto($nbTelechargementsAuto)
{
$this->nbTelechargementsAuto = $nbTelechargementsAuto;
return $this;
}
/**
* Get nbTelechargementsAuto
*
* #return int
*/
public function getNbTelechargementsAuto()
{
return $this->nbTelechargementsAuto;
}
/**
* Set isActif
*
* #param boolean $isActif
*
* #return User
*/
public function setIsActif($isActif)
{
$this->isActif = $isActif;
return $this;
}
/**
* Get isActif
*
* #return bool
*/
public function getIsActif()
{
return $this->isActif;
}
/**
* Set isCreated
*
* #param boolean $isCreated
*
* #return User
*/
public function setIsCreated($isCreated)
{
$this->isCreated = $isCreated;
return $this;
}
/**
* Get isCreated
*
* #return bool
*/
public function getIsCreated()
{
return $this->isCreated;
}
public function __construct()
{
$this->roles = ['ROLE_USER'];
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($password)
{
$this->plainPassword = $password;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getRoles()
{
return $this->roles;
}
public function eraseCredentials()
{
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize([
$this->id,
$this->username,
$this->password,
$this->email,
$this->nbTelechargementsAuto,
$this->nom,
$this->prenom,
// see section on salt below
// $this->salt,
]);
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
$this->email,
$this->nbTelechargementsAuto,
$this->nom,
$this->prenom,
// see section on salt below
// $this->salt
) = unserialize($serialized, ['allowed_classes' => false]);
}
/**
* Activation du compte
*/
public function activerCompte($nbPackages, $nbHomonymes)
{
if($this->getIsCreated() == 0)
{
$unUsername = $this->getNom();
$unUsername .= ".";
$unUsername .= $this->getPrenom();
$unUsername = strtolower($unUsername);
if($nbHomonymes > 0)
{
$nbHomonymes++;
$unUsername .= $nbHomonymes;
}
$this->setUsername(strtolower($unUsername));
$this->setNbTelechargementsAuto($nbPackages);
$this->setCreatedAt();
$this->setIsCreated(true);
}
$password = $this->generatePassword();
$this->setPlainPassword($password);
$this->setIsActif(true);
return $this;
}
public function constructionUsername()
{
$unUsername = $this->getNom();
$unUsername .= ".";
$unUsername .=$this->getPrenom();
return $unUsername;
}
/**
* Désactivation du compte
*/
public function desactiverCompte()
{
$this->setIsActif(false);
$this->setCreatedAt();
return $this;
}
public function registration()
{
// Passage Nom 1ère lettre Majuscule le reste minuscule
$leNom = $this->getNom();
$leNom = strtolower($leNom);
$leNom = ucfirst($leNom);
// Passage Nom 1ère lettre Majuscule le reste minuscule
$lePrenom = $this->getPrenom();
$lePrenom = strtolower($lePrenom);
$lePrenom = ucfirst($lePrenom);
$this->setNom($leNom);
$this->setPrenom($lePrenom);
$this->setCreatedAt();
}
/**
* Génération d'un mot de passe
* $nb_caractere = nombre de caractère du mdp
* Pas de caractère qui se ressemble (L minuscule, 1 et i majuscule, Zéro et la lettre o.)
* Sécurité supplémentaire avec : caractères speciaux: - + = $ % ! # #
* Pas d'espace pour éviter les erreurs
*/
function generatePassword($nb_caractere = 7)
{
$mot_de_passe = "";
$chaine = "abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ023456789#!$?&";
$longeur_chaine = strlen($chaine);
for($i = 1; $i <= $nb_caractere; $i++)
{
$place_aleatoire = mt_rand(0,($longeur_chaine-1));
$mot_de_passe .= $chaine[$place_aleatoire];
}
return $mot_de_passe;
}
}
config.php:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: en
framework:
# ...
templating:
engines: ['twig']
#esi: ~
#translator: { fallbacks: ['%locale%'] }
secret: '%secret%'
router:
resource: '%kernel.project_dir%/app/config/routing.yml'
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
default_locale: '%locale%'
trusted_hosts: ~
session:
# https://symfony.com/doc/current/reference/configuration/framework.html#handler-id
handler_id: session.handler.native_file
save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
fragments: ~
http_method_override: true
assets: ~
php_errors:
log: true
# Twig Configuration
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
form_themes: ['bootstrap_4_layout.html.twig']
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
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:
# 1. add the path in parameters.yml
# e.g. database_path: '%kernel.project_dir%/var/data/data.sqlite'
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
#path: '%database_path%'
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
sensio_framework_extra:
router:
annotations: false
assetic:
debug: "%kernel.debug%"
use_controller: false
bundles: [ ]
#java: /usr/bin/java
java: C:\Program Files\Java\jdk1.8.0_65\bin\java.exe
filters:
cssrewrite: ~
cssembed:
jar: "%kernel.root_dir%/Resources/java/cssembed.jar"
yui_js:
jar: "%kernel.root_dir%/Resources/java/yuicompressor.jar"
yui_css:
jar: "%kernel.root_dir%/Resources/java/yuicompressor.jar"
lessphp:
file: "%kernel.root_dir%/../vendor/oyejorge/less.php/lessc.inc.php"
apply_to: ".less$"
assets:
jquery_js:
inputs:
- "%kernel.root_dir%/../vendor/components/jquery/jquery.min.js"
filters: [?yui_js]
output: js/jquery.min.js
bootstrap_css:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/less/bootstrap.less"
filters:
- lessphp
- cssrewrite
output: css/bootstrap.css
bootstrap_js:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/affix.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/alert.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/button.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/carousel.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/collapse.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/dropdown.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/modal.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/tooltip.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/popover.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/scrollspy.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/tab.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/transition.js"
filters: [?yui_js]
output: js/bootstrap.js
fonts_glyphicons_eot:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.eot"
output: "fonts/glyphicons-halflings-regular.eot"
fonts_glyphicons_svg:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.svg"
output: "fonts/glyphicons-halflings-regular.svg"
fonts_glyphicons_ttf:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.ttf"
output: "fonts/glyphicons-halflings-regular.ttf"
fonts_glyphicons_woff:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.woff"
output: "fonts/glyphicons-halflings-regular.woff"
stof_doctrine_extensions:
orm:
default:
sluggable: true
vich_uploader:
db_driver: orm
twig: true
storage: file_system
mappings:
paquet:
uri_prefix: fichiers/packages
upload_destination: '%kernel.root_dir%/../web/fichiers/packages/'
inject_on_load: true
delete_on_update: true
delete_on_remove: true
notice:
uri_prefix: fichiers/notices
upload_destination: '%kernel.root_dir%/../web/fichiers/notices/'
inject_on_load: false
delete_on_update: true
delete_on_remove: true
fos_ck_editor:
configs:
my_config:
toolbar: [ ["Source", "-", "Save"], "/", ["Anchor"], "/", ["Maximize"] ]
uiColor: "#000000"
Security.yml :
# To get started with security, check out the documentation:
# https://symfony.com/doc/current/security.html
security:
encoders:
Site\PagesBundle\Entity\User: bcrypt
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]
# https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
providers:
in_memory: {memory: ~}
in_database:
entity:
class: Site\PagesBundle\Entity\User
property: username
our_db_provider:
entity:
class: Site\PagesBundle\Entity\User
property: username
# if you're using multiple entity managers
# manager_name: customer
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
provider: in_database
form_login:
login_path: security_login
check_path: security_login
logout:
path: security_logout
target: informations
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
#http_basic: ~
# https://symfony.com/doc/current/security/form_login_setup.html
#form_login: ~
And a part fo the controller that I use to manage what is relative to the navigation of the user, including its authentication
DefaultController.php :
<?php
namespace Site\PagesBundle\Controller;
use Site\PagesBundle\Entity\User;
use Site\PagesBundle\Entity\Paquet;
use Site\PagesBundle\Entity\TypeUser;
use Site\PagesBundle\Entity\Information;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Vich\UploaderBundle\Handler\DownloadHandler;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
/**
* Default controller.
*
* #Route("accueil")
*/
class DefaultController extends Controller
{
/**
* Accueil
*
* #Route("/", name="connexion_index")
* #Method({"GET", "POST"})
*/
public function indexAction(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$em = $this->getDoctrine()->getManager(); //Récupération du manager
$listeInfos = $em->getRepository('PagesBundle:Information')->getInformationsZone("Zone 1"); //Récupération d'une liste d'informations
$user = new User(); //Initialisation de l'objet User
$form = $this->createForm('Site\PagesBundle\Form\ConnexionType', $user); //Formulaire de création
$form->handleRequest($request);
//Traitement si le formulaire est soumis ( Ajout du package dans la BDD )
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$valide = $this->getDoctrine()->getManager()->getRepository('PagesBundle:User')->authentifier($user->getUsername(),$password);
dump($valide);
dump($password);
if($valide == 1)
{
return $this->redirectToRoute('accueil');
}
else
{
return $this->render('#Pages/Default/connexion.html.twig',array(
'user' => $user,
'form' => $form->createView(),
'listeInfos' => $listeInfos,
));
}
// On ajoute un package, donc on offre un téléchargement supplémentaire aux utilisateurs concernés
$this->getDoctrine()->getManager()->getRepository('PagesBundle:User')->updateNbDDLAll("inc");
//return $this->redirectToRoute('paquets_index'); // Redirection page de gestion de packages
}
return $this->render('#Pages/Default/connexion.html.twig',array(
'user' => $user,
'form' => $form->createView(),
'listeInfos' => $listeInfos,
));
}
Thanks for your help !
EDIT:
My function :
/**
* Accueil
*
* #Route("/", name="connexion_index")
* #Method({"GET", "POST"})
*/
public function indexAction(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$em = $this->getDoctrine()->getManager(); //Récupération du manager
$listeInfos = $em->getRepository('PagesBundle:Information')->getInformationsZone("Zone 1"); //Récupération d'une liste d'informations
$user = new User(); //Initialisation de l'objet User
$form = $this->createForm('Site\PagesBundle\Form\ConnexionType', $user); //Formulaire de création
$form->handleRequest($request);
//Traitement si le formulaire est soumis ( Ajout du package dans la BDD )
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$valide = $this->getDoctrine()->getManager()->getRepository('PagesBundle:User')->authentifier($user->getUsername(),$password);
dump($valide);
dump($password);
if($valide == 1)
{
return $this->redirectToRoute('accueil');
}
else
{
return $this->render('#Pages/Default/connexion.html.twig',array(
'user' => $user,
'form' => $form->createView(),
'listeInfos' => $listeInfos,
));
}
// On ajoute un package, donc on offre un téléchargement supplémentaire aux utilisateurs concernés
$this->getDoctrine()->getManager()->getRepository('PagesBundle:User')->updateNbDDLAll("inc");
//return $this->redirectToRoute('paquets_index'); // Redirection page de gestion de packages
}
I retrieve the password entered by the user in the login form.
I encrypt it. Then I run a check in my UserRepository with the username and password encrypted.
If the function returns true, there is someone who has the username entered and the encrypted password entered.
My UserRepository function :
public function authentifier($username, $password)
{
$queryBuilder = $this->createQueryBuilder("u")
->select("count(u.id)")
->where("u.username = :username")
->andWhere("u.password = :password")
->setParameter("username",$username)
->setParameter("password",$password);
return $queryBuilder->getQuery()->getSingleScalarResult();
}
}
However, what is the cost in the security.yml?
To check if the posted password on your login form match with the one in database, you just need to bcrypt it and check if it's the same as the one in db.
You get your User from db
you encode the posted password
You check if the posted encoded password is the same as the one sotred in your User
But in your Controller code, it seems you create a new user (you create a new User instrad of getting one from db, and you persist it) ?

Symfony 3.4 - Incorrectly configured services

I am trying to encrypt the passwords of my Users table using the functions provided by Symfony 3.4.
My goal would be as follows:
Generate a random password of 7 characters (including special characters) ==> Done.
Encrypt the password and insert it into the database. ==> Failed
Be able to check when the user enters their password (one that is not encrypted) to authenticate. ==> Failed.
For the 1st step I used this function:
function generatePassword($nb_caractere = 7)
{
$mot_de_passe = "";
$chaine = "abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ023456789#!$?&";
$longeur_chaine = strlen($chaine);
for($i = 1; $i <= $nb_caractere; $i++)
{
$place_aleatoire = mt_rand(0,($longeur_chaine-1));
$mot_de_passe .= $chaine[$place_aleatoire];
}
return $mot_de_passe;
}
The password is correctly generated.
For the second step, my idea was to use this:
$encoded = $encoder->encodePassword($user, $user->getPassword());
But I've this error :
Controller
"Site\PagesBundle\Controller\UserController::activerUtilisateur()"
requires that you provide a value for the "$encoder" argument. Either
the argument is nullable and no null value has been provided, no
default value has been provided or because there is a non optional
argument after this one.
I send you the code of my files for more details :
User.php :
<?php
namespace Site\PagesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="Site\PagesBundle\Repository\UserRepository")
*/
class User
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="identifiant", type="string", length=255, nullable=true)
*/
private $identifiant;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="prenom", type="string", length=255)
*/
private $prenom;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=true)
*/
private $password;
/**
* #var int
*
* #ORM\Column(name="nbTelechargementsAuto", type="integer", nullable=true)
*/
private $nbTelechargementsAuto;
/**
* #var bool
*
* #ORM\Column(name="isActif", type="boolean")
*/
private $isActif=0;
/**
* #ORM\Column(type="datetime", nullable=true)
*
* #var \DateTime
*/
private $createdAt;
/**
* #var bool
*
* #ORM\Column(name="isCreated", type="boolean")
*/
private $isCreated=0;
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Information
*/
public function setCreatedAt()
{
$this->createdAt = new \DateTimeImmutable();
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
*
* #return User
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set nom
*
* #param string $identifiant
*
* #return User
*/
public function setIdentifiant($identifiant)
{
$this->identifiant = $identifiant;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getIdentifiant()
{
return $this->identifiant;
}
/**
* Set prenom
*
* #param string $prenom
*
* #return User
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set nbTelechargementsAuto
*
* #param integer $nbTelechargementsAuto
*
* #return User
*/
public function setNbTelechargementsAuto($nbTelechargementsAuto)
{
$this->nbTelechargementsAuto = $nbTelechargementsAuto;
return $this;
}
/**
* Get nbTelechargementsAuto
*
* #return int
*/
public function getNbTelechargementsAuto()
{
return $this->nbTelechargementsAuto;
}
/**
* Set isActif
*
* #param boolean $isActif
*
* #return User
*/
public function setIsActif($isActif)
{
$this->isActif = $isActif;
return $this;
}
/**
* Get isActif
*
* #return bool
*/
public function getIsActif()
{
return $this->isActif;
}
/**
* Set isCreated
*
* #param boolean $isCreated
*
* #return User
*/
public function setIsCreated($isCreated)
{
$this->isCreated = $isCreated;
return $this;
}
/**
* Get isCreated
*
* #return bool
*/
public function getIsCreated()
{
return $this->isCreated;
}
/**
* Activation du compte
*/
public function activerCompte($nbPackages, $nbHomonymes)
{
if($this->getIsCreated() == 0)
{
$unIdentifiant = $this->getNom();
$unIdentifiant .= ".";
$unIdentifiant .= $this->getPrenom();
$unIdentifiant = strtolower($unIdentifiant);
if($nbHomonymes > 0)
{
$nbHomonymes++;
$unIdentifiant .= $nbHomonymes;
}
$this->setIdentifiant(strtolower($unIdentifiant));
$this->setNbTelechargementsAuto($nbPackages);
$this->setCreatedAt();
$this->setIsCreated(true);
}
$password = $this->generatePassword();
$this->setPassword($password);
$this->setIsActif(true);
return $this;
}
public function constructionIdentifiant()
{
$unIdentifiant = $this->getNom();
$unIdentifiant .= ".";
$unIdentifiant .=$this->getPrenom();
return $unIdentifiant;
}
/**
* Désactivation du compte
*/
public function desactiverCompte()
{
$this->setIsActif(false);
$this->setCreatedAt();
return $this;
}
public function registration()
{
// Passage Nom 1ère lettre Majuscule le reste minuscule
$leNom = $this->getNom();
$leNom = strtolower($leNom);
$leNom = ucfirst($leNom);
// Passage Nom 1ère lettre Majuscule le reste minuscule
$lePrenom = $this->getPrenom();
$lePrenom = strtolower($lePrenom);
$lePrenom = ucfirst($lePrenom);
$this->setNom($leNom);
$this->setPrenom($lePrenom);
$this->setCreatedAt();
}
/**
* Génération d'un mot de passe
* $nb_caractere = nombre de caractère du mdp
* Pas de caractère qui se ressemble (L minuscule, 1 et i majuscule, Zéro et la lettre o.)
* Sécurité supplémentaire avec : caractères speciaux: - + = $ % ! # #
* Pas d'espace pour éviter les erreurs
*/
function generatePassword($nb_caractere = 7)
{
$mot_de_passe = "";
$chaine = "abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ023456789#!$?&";
$longeur_chaine = strlen($chaine);
for($i = 1; $i <= $nb_caractere; $i++)
{
$place_aleatoire = mt_rand(0,($longeur_chaine-1));
$mot_de_passe .= $chaine[$place_aleatoire];
}
return $mot_de_passe;
}
}
Controller :
<?php
namespace Site\PagesBundle\Controller;
use Site\PagesBundle\Entity\User;
use Symfony\Component\HttpFoundation\Request;
use Site\PagesBundle\Utils\Functions as mesFonctions;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
/**
* User controller.
*
* #Route("utilisateurs")
*/
class UserController extends Controller
{
//... Some functions
/**
* Activer le compte d'un utilisateur
*
* #Route("/activer/{id}", name="utilisateur_activation")
* #Method("GET")
*/
public function activerUtilisateur(UserPasswordEncoderInterface $encoder,Request $request, $id)
{
$em = $this->getDoctrine()->getManager(); //Récupération du manager
$nbPackages = $em->getRepository('PagesBundle:Paquet')->getNombrePackages(); //Récupération du nombre de packages (pour initialiser le nombre de téléchargements offert à l'utilisateur)
$user = $em->getRepository('PagesBundle:User')->findOneById($id); // Récupération de l'objet User en fonction de l'ID fourni en paramètre
// $lesUtilisateurs = $em->getRepository('PagesBundle:User')->findAll();
$nbHomonymes = $em->getRepository('PagesBundle:User')->getHomonymes($user->getNom(),$user->getPrenom()); //Vérification des homonymes pour attribuer un bon identifiant pour l'utilisateur activé
$user->activerCompte($nbPackages,$nbHomonymes); //Procédure d'activation du compte
$em->persist($user); //Enregistrement des informations du compte
$encoded = $encoder->encodePassword($user, $user->getPassword());
$user->setPassword($encoded);
$em->flush(); //Validation dans la bDD
mesFonctions::sendMail($user->getEmail(),"confirmation",$user->getIdentifiant()); //Envoi d'un mail à l'utilisateur sur l'adresse mail qu'il a renseigné lors de sa demande d'inscription
return $this->redirectToRoute('utilisateurs_index'); //Redirection à la liste des différents utilisateurs
}
Security.yml: I did not touch this part but I wonder if she has an interest. I do not know too much about symfony.
# To get started with security, check out the documentation:
# https://symfony.com/doc/current/security.html
security:
encoders:
PagesBundle\Entity\User: bcrypt
# https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
providers:
in_memory: {memory: ~}
in_database:
entity:
class: Site\PagesBundle\Entity\User
property: email
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
provider: in_database
form_login:
login_path: security_login
check_path: security_login
logout:
path: security_logout
target: informations
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
#http_basic: ~
# https://symfony.com/doc/current/security/form_login_setup.html
#form_login: ~
Thanks !
EDIT:
config :
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: en
framework:
# ...
templating:
engines: ['twig']
#esi: ~
#translator: { fallbacks: ['%locale%'] }
secret: '%secret%'
router:
resource: '%kernel.project_dir%/app/config/routing.yml'
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
default_locale: '%locale%'
trusted_hosts: ~
session:
# https://symfony.com/doc/current/reference/configuration/framework.html#handler-id
handler_id: session.handler.native_file
save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
fragments: ~
http_method_override: true
assets: ~
php_errors:
log: true
# Twig Configuration
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
form_themes: ['bootstrap_4_layout.html.twig']
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
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:
# 1. add the path in parameters.yml
# e.g. database_path: '%kernel.project_dir%/var/data/data.sqlite'
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
#path: '%database_path%'
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
sensio_framework_extra:
router:
annotations: false
assetic:
debug: "%kernel.debug%"
use_controller: false
bundles: [ ]
#java: /usr/bin/java
java: C:\Program Files\Java\jdk1.8.0_65\bin\java.exe
filters:
cssrewrite: ~
cssembed:
jar: "%kernel.root_dir%/Resources/java/cssembed.jar"
yui_js:
jar: "%kernel.root_dir%/Resources/java/yuicompressor.jar"
yui_css:
jar: "%kernel.root_dir%/Resources/java/yuicompressor.jar"
lessphp:
file: "%kernel.root_dir%/../vendor/oyejorge/less.php/lessc.inc.php"
apply_to: ".less$"
assets:
jquery_js:
inputs:
- "%kernel.root_dir%/../vendor/components/jquery/jquery.min.js"
filters: [?yui_js]
output: js/jquery.min.js
bootstrap_css:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/less/bootstrap.less"
filters:
- lessphp
- cssrewrite
output: css/bootstrap.css
bootstrap_js:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/affix.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/alert.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/button.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/carousel.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/collapse.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/dropdown.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/modal.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/tooltip.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/popover.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/scrollspy.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/tab.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/transition.js"
filters: [?yui_js]
output: js/bootstrap.js
fonts_glyphicons_eot:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.eot"
output: "fonts/glyphicons-halflings-regular.eot"
fonts_glyphicons_svg:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.svg"
output: "fonts/glyphicons-halflings-regular.svg"
fonts_glyphicons_ttf:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.ttf"
output: "fonts/glyphicons-halflings-regular.ttf"
fonts_glyphicons_woff:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.woff"
output: "fonts/glyphicons-halflings-regular.woff"
stof_doctrine_extensions:
orm:
default:
sluggable: true
vich_uploader:
db_driver: orm
twig: true
storage: file_system
mappings:
paquet:
uri_prefix: fichiers/packages
upload_destination: '%kernel.root_dir%/../web/fichiers/packages/'
inject_on_load: true
delete_on_update: true
delete_on_remove: true
notice:
uri_prefix: fichiers/notices
upload_destination: '%kernel.root_dir%/../web/fichiers/notices/'
inject_on_load: false
delete_on_update: true
delete_on_remove: true
fos_ck_editor:
configs:
my_config:
toolbar: [ ["Source", "-", "Save"], "/", ["Anchor"], "/", ["Maximize"] ]
uiColor: "#000000"
services.yml:
# Learn more about services, parameters and containers at
# https://symfony.com/doc/current/service_container.html
parameters:
#parameter_name: value
services:
# default configuration for services in *this* file
_defaults:
# automatically injects dependencies in your services
autowire: true
# automatically registers your services as commands, event subscribers, etc.
autoconfigure: true
# this means you cannot fetch services directly from the container via $container->get()
# if you need to do this, you can override this setting on individual services
public: false
# makes classes in src/AppBundle available to be used as services
# this creates a service per class whose id is the fully-qualified class name
AppBundle\:
resource: '../../src/AppBundle/*'
# you can exclude directories or files
# but if a service is unused, it's removed anyway
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
# controllers are imported separately to make sure they're public
# and have a tag that allows actions to type-hint services
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
twig.extension.intl:
class: Twig_Extensions_Extension_Intl
tags:
- { name: twig.extension }
# add more services, or override services that need manual wiring
# AppBundle\Service\ExampleService:
# arguments:
# $someArgument: 'some_value'
Ok I get it.
You have multiple bundles based on the UserController namespace (Site\PagesBundle\Controller\UserController). But your services.yaml enable services only for your AppBundle.
you have to duplicate this configuration for all your bundles and adapt it with the right namespace :
#services.yaml file
AppBundle\:
resource: '../../src/AppBundle/*'
# you can exclude directories or files
# but if a service is unused, it's removed anyway
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
# controllers are imported separately to make sure they're public
# and have a tag that allows actions to type-hint services
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
This will declare all your controllers from your bundles as services in order to enable autowiring service in controllers constructors or in controllers actions.
Edit with example for your bundle:
Site\PagesBundle\:
resource: '../../src/Site/PagesBundle/*'
exclude: '../../src/Site/PagesBundle/{Entity,Repository,Tests}'
# controllers are imported separately to make sure they're public
# and have a tag that allows actions to type-hint services
Site\PagesBundle\Controller\:
resource: '../../src/Site/PagesBundle/Controller'
public: true
tags: ['controller.service_arguments']

The class 'App\Document\User' was not found in the chain configured namespaces

I have just put in place mongodb with symfony4.1.
When I want to persist a simple User in the database, I got this error (title) :
Uncaught PHP Exception Doctrine\Common\Persistence\Mapping\MappingException: "The class 'App\Document\User' was not found in the chain configured namespaces
Here my controller :
/**
* #Route("/mongoTest")
* #Method("GET")
* #param DocumentManager $dm
* #return JsonResponse
*/
public function mongoTest(DocumentManager $dm)
{
$user = new User();
$user->setEmail("hello#medium.com");
$user->setFirstname("Matt");
$user->setLastname("Matt");
$user->setPassword(md5("123456"));
$dm->persist($user);
$dm->flush();
return new JsonResponse(array('Status' => 'OK'));
}
Config :
doctrine_mongodb:
connections:
default:
server: "%mongodb_server%"
options: {}
default_database: "%mongodb_database_name%"
document_managers:
default:
auto_mapping: true
default_commit_options: ~
Here my Document :
<?php
namespace App\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class User
{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\Field(type="string")
*/
protected $firstname;
/**
* #MongoDB\Field(type="string")
*/
protected $lastname;
/**
* #MongoDB\Field(type="string")
*/
protected $email;
/**
* #MongoDB\Field(type="string")
*/
protected $password;
/**
* #MongoDB\Field(type="date")
*/
protected $create_date;
// ...
}
Does anyone have an idea ?
Thanks a lot !!
I found the answer :
I do not use bundles.
doctrine_mongodb:
connections:
default:
server: "%mongodb_server%"
options: {}
default_database: "%mongodb_database_name%"
document_managers:
default:
mappings:
# ...
App:
type: annotation
dir: "%kernel.root_dir%/../src/Document"
is_bundle: false
prefix: App\Document
alias: App
default_commit_options: ~

Symfony Gedmo Blameable not working

Did any one ever find an solution for this issue?
I'm having the same issue.
My config.yml:
# Doctrine Configuration
doctrine:
dbal:
driver: "%database_server%"
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:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
#Gedmo Package extension for Symfony and Doctrine
mappings:
gedmo_tree:
type: annotation
prefix: Gedmo\Tree\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity"
alias: GedmoTree
is_bundle: false
gedmo_sortable:
type: annotation
prefix: Gedmo\Sortable\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Sortable/Entity"
alias: GedmoTree
is_bundle: false
[...]
stof_doctrine_extensions:
default_locale: "%locale%"
translation_fallback: true
orm:
default:
timestampable: true
blameable: true
My doctrine_extension.yml is included in the config file:
services:
extension.listener:
class: Omega\HomeBundle\Library\Listener\DoctrineExtensionListener
calls:
- [ setContainer, [#service_container]]
tags:
# loggable hooks user username if one is in security context
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
# Doctrine Extension listeners to handle behaviors
gedmo.listener.tree:
class: Gedmo\Tree\TreeListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ #annotation_reader ] ]
gedmo.listener.sortable:
class: Gedmo\Sortable\SortableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ #annotation_reader ] ]
gedmo.listener.timestampable:
class: Gedmo\Timestampable\TimestampableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ #annotation_reader ] ]
gedmo.listener.loggable:
class: Gedmo\Loggable\LoggableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ #annotation_reader ] ]
gedmo.listener.blameable:
class: Gedmo\Blameable\BlameableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ #annotation_reader ] ]
- [ setUserValue, [ #security.token_storage ] ]
I created myself an trait to handle the created, updated, updated_by and createdby fields:
namespace HomeBundle\Traits;
use Doctrine\ORM\Mapping as ORM;
use Omega\UserBundle\Entity\Users;
use Gedmo\Mapping\Annotation as Gedmo;
trait LogableTrait
{
/**
* #var Users
* #Gedmo\Blameable(on="create")
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\Users")
* #ORM\JoinColumn(name="log_created_by", referencedColumnName="id")
*/
protected $CreatedBy;
/**
* #var Users
* #Gedmo\Blameable(on="update")
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\Users")
* #ORM\JoinColumn(name="log_updated_by", referencedColumnName="id")
*/
protected $UpdatedBy;
/**
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="created", type="datetime")
* #var \DateTime
*/
protected $created;
/**
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="updated", type="datetime")
* #var \DateTime
*/
protected $updated;
/**
* #return Users
*/
public function getCreatedBy ()
{
return $this->CreatedBy;
}
/**
* #param Users $CreatedBy
*
* #return $this
*/
public function setCreatedBy (Users $CreatedBy )
{
$this->CreatedBy = $CreatedBy;
return $this;
}
/**
* #return Users
*/
public function getUpdatedBy ()
{
return $this->UpdatedBy;
}
/**
* #param Users $UpdatedBy
*
* #return $this
*/
public function setUpdatedBy (Users $UpdatedBy )
{
$this->UpdatedBy = $UpdatedBy;
return $this;
}
}
But everytime that I use this Bundle I get:
The class 'Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage' was not found in the chain configured namespaces Gedmo\Tree\Entity, Gedmo\Sortable\Entity, JMS\JobQueueBundle\Entity, AccountingBundle\Entity, DocumentsBundle\Entity, EavBundle\Entity, HomeBundle\Entity, UserBundle\Entity, CustomerBundle\Entity, Jns\Bundle\XhprofBundle\Entity
I hope some body can help me.
for any one that Is having th same issue like me that the blamable feature is not working:
My solution was to implement the BlamableListener with an different approach:
namespace HomeBundle\Library;
use Doctrine\Common\NotifyPropertyChanged;
use Gedmo\Exception\InvalidArgumentException;
use Gedmo\Timestampable\TimestampableListener;
use Gedmo\Blameable\Mapping\Event\BlameableAdapter;
use Gedmo\Blameable\Mapping\Driver\Annotation;
/**
* The Blameable listener handles the update of
* dates on creation and update.
*
* #author Gediminas Morkevicius <gediminas.morkevicius#gmail.com>
* #license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class BlameableListener extends TimestampableListener
{
protected $user;
/**
* Get the user value to set on a blameable field
*
* #param object $meta
* #param string $field
*
* #return mixed
*/
public function getUserValue($meta, $field)
{
if ($meta->hasAssociation($field)) {
if (null !== $this->user && ! is_object($this->user)) {
throw new InvalidArgumentException("Blame is reference, user must be an object");
}
$user = $this->user->getToken()->getUser();
if(!is_object($user))
{
return null;
}
return $user;
}
// ok so its not an association, then it is a string
if (is_object($this->user)) {
if (method_exists($this->user, 'getUsername')) {
return (string) $this->user->getUsername();
}
if (method_exists($this->user, '__toString')) {
return $this->user->__toString();
}
throw new InvalidArgumentException("Field expects string, user must be a string, or object should have method getUsername or __toString");
}
return $this->user;
}
/**
* Set a user value to return
*
* #param mixed $user
*/
public function setUserValue($user)
{
$this->user = $user;
}
/**
* {#inheritDoc}
*/
protected function getNamespace()
{
return __NAMESPACE__;
}
/**
* Updates a field
*
* #param object $object
* #param BlameableAdapter $ea
* #param $meta
* #param $field
*/
protected function updateField($object, $ea, $meta, $field)
{
$property = $meta->getReflectionProperty($field);
$oldValue = $property->getValue($object);
$newValue = $this->getUserValue($meta, $field);
//if blame is reference, persist object
if ($meta->hasAssociation($field) && $newValue) {
$ea->getObjectManager()->persist($newValue);
}
$property->setValue($object, $newValue);
if ($object instanceof NotifyPropertyChanged) {
$uow = $ea->getObjectManager()->getUnitOfWork();
$uow->propertyChanged($object, $field, $oldValue, $newValue);
}
}
}
adjust the service for the blamable:
gedmo.listener.blameable:
class: HomeBundle\Library\BlameableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ #annotation_reader ] ]
- [ setUserValue, [ #security.token_storage ] ]
you need to copy the mapping library to the same location as the listener itself. Adjust the namespaces and it works. It seems that some structures changed in symfony 2.7 so the plugin no longer works out of the box.
If you want to update the updated_by field, you must specify the field so that when you update it, do so in updated_by. For example:
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime", nullable=true)
*/
protected $updated;
/**
* #var string $updatedBy
*
* #Gedmo\Blameable(on="update", field="updated")
* #ORM\Column(type="string", nullable=true)
*/
protected $updatedBy;
Pay attention to field="updated"
Just create DoctrineExtensionSubscriber
Manually tag the listeners
Gedmo\Loggable\LoggableListener:
tags:
- { name: doctrine_mongodb.odm.event_subscriber }
Create DoctrineExtensionSubscriber
<?php
namespace App\EventSubscriber;
use Gedmo\Blameable\BlameableListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class DoctrineExtensionSubscriber implements EventSubscriberInterface
{
/**
* #var BlameableListener
*/
private $blameableListener;
/**
* #var TokenStorageInterface
*/
private $tokenStorage;
/**
* #var TranslatableListener
*/
private $translatableListener;
/**
* #var LoggableListener
*/
private $loggableListener;
public function __construct(
BlameableListener $blameableListener,
TokenStorageInterface $tokenStorage,
TranslatableListener $translatableListener,
LoggableListener $loggableListener
) {
$this->blameableListener = $blameableListener;
$this->tokenStorage = $tokenStorage;
$this->translatableListener = $translatableListener;
$this->loggableListener = $loggableListener;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
KernelEvents::FINISH_REQUEST => 'onLateKernelRequest'
];
}
public function onKernelRequest(): void
{
if ($this->tokenStorage !== null &&
$this->tokenStorage->getToken() !== null &&
$this->tokenStorage->getToken()->isAuthenticated() === true
) {
$this->blameableListener->setUserValue($this->tokenStorage->getToken()->getUser());
}
}
public function onLateKernelRequest(FinishRequestEvent $event): void
{
$this->translatableListener->setTranslatableLocale($event->getRequest()->getLocale());
}
}

ReflectionException with Symfony and Sonata, "Class does not exist"

I'm experiencing a problem trying to fit my Entities in the Sonata Admin Bundle. I have something like 5 entities, which are finely listed and viewed in the bundle, but I cannot edit or create a new entry.
When I try to edit or create, I get a ReflectionException error:
Class does not exist
I tried in order to solve that problem to operate on namespaces (moving controller in the same namespace that Admin files, or so) or to tweak the Admin Controller in order to tell it about my entities ("->add('individual', 'entity', array('class' => 'Platform\ProjectBundle\Entity\Individual'))" instead of ->add('individual')).
My entity is named Biosample. Here is the Entity file:
<?php
namespace Platform\ProjectBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="biosample")
*/
class Biosample
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Individual", inversedBy="samples")
* #ORM\JoinColumn(name="individual_id", referencedColumnName="id")
*/
protected $individual;
/**
* #ORM\Column(type="string", length=100)
*/
protected $organ;
/**
* #ORM\Column(type="string", length=100)
*/
protected $sample_name;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $organ_location;
/**
* #ORM\Column(type="string")
*/
protected $tissue_type;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $tissue_subtype;
/**
* #ORM\Column(type="datetimetz")
*/
protected $sampling_date;
/**
* #ORM\Column(type="decimal", scale=3, nullable=true)
*/
protected $cellularity;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $conservation;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $description;
/**
* #ORM\ManyToMany(targetEntity="Project", mappedBy="biosamples")
*/
protected $projects;
public function __construct()
{
$this->projects = new ArrayCollection();
}
public function __toString()
{
return $this->sample_name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set organ
*
* #param string $organ
* #return Biosample
*/
public function setOrgan($organ)
{
$this->organ = $organ;
return $this;
}
/**
* Get organ
*
* #return string
*/
public function getOrgan()
{
return $this->organ;
}
/**
* Set organ_location
*
* #param string $organLocation
* #return Biosample
*/
public function setOrganLocation($organLocation)
{
$this->organ_location = $organLocation;
return $this;
}
/**
* Get organ_location
*
* #return string
*/
public function getOrganLocation()
{
return $this->organ_location;
}
/**
* Set tissue_type
*
* #param string $tissueType
* #return Biosample
*/
public function setTissueType($tissueType)
{
$this->tissue_type = $tissueType;
return $this;
}
/**
* Get tissue_type
*
* #return string
*/
public function getTissueType()
{
return $this->tissue_type;
}
/**
* Set tissue_subtype
*
* #param string $tissueSubtype
* #return Biosample
*/
public function setTissueSubtype($tissueSubtype)
{
$this->tissue_subtype = $tissueSubtype;
return $this;
}
/**
* Get tissue_subtype
*
* #return string
*/
public function getTissueSubtype()
{
return $this->tissue_subtype;
}
/**
* Set sampling_date
*
* #param \DateTime $samplingDate
* #return Biosample
*/
public function setSamplingDate($samplingDate)
{
$this->sampling_date = $samplingDate;
return $this;
}
/**
* Get sampling_date
*
* #return \DateTime
*/
public function getSamplingDate()
{
return $this->sampling_date;
}
/**
* Set cellularity
*
* #param string $cellularity
* #return Biosample
*/
public function setCellularity($cellularity)
{
$this->cellularity = $cellularity;
return $this;
}
/**
* Get cellularity
*
* #return string
*/
public function getCellularity()
{
return $this->cellularity;
}
/**
* Set conservation
*
* #param string $conservation
* #return Biosample
*/
public function setConservation($conservation)
{
$this->conservation = $conservation;
return $this;
}
/**
* Get conservation
*
* #return string
*/
public function getConservation()
{
return $this->conservation;
}
/**
* Set description
*
* #param string $description
* #return Biosample
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set individual
*
* #param \Platform\ProjectBundle\Entity\Individual $individual
* #return Biosample
*/
public function setIndividual(\Platform\ProjectBundle\Entity\Individual $individual = null)
{
$this->individual = $individual;
return $this;
}
/**
* Get individual
*
* #return \Platform\ProjectBundle\Entity\Individual
*/
public function getIndividual()
{
return $this->individual;
}
/**
* Add projects
*
* #param \Platform\ProjectBundle\Entity\Project $projects
* #return Biosample
*/
public function addProject(\Platform\ProjectBundle\Entity\Project $projects)
{
$this->projects[] = $projects;
return $this;
}
/**
* Remove projects
*
* #param \Platform\ProjectBundle\Entity\Project $projects
*/
public function removeProject(\Platform\ProjectBundle\Entity\Project $projects)
{
$this->projects->removeElement($projects);
}
/**
* Get projects
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProjects()
{
return $this->projects;
}
/**
* Set sample_name
*
* #param string $sampleName
* #return Biosample
*/
public function setSampleName($sampleName)
{
$this->sample_name = $sampleName;
return $this;
}
/**
* Get sample_name
*
* #return string
*/
public function getSampleName()
{
return $this->sample_name;
}
}`
Here is my BiosampleAdmin.php:
<?php
namespace Platform\ProjectBundle\Controller\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Knp\Menu\ItemInterface as MenuItemInterface;
use Platform\ProjectBundle\Entity\Biosample;
class BiosampleAdmin extends Admin
{
/**
* #param \Sonata\AdminBundle\Show\ShowMapper $showMapper
*
* #return void
*/
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('id')
->add('sample_name')
->add('individual', 'entity', array('class' => 'Platform\ProjectBundle\Entity\Individual'))
->add('organ')
->add('organ_location')
->add('tissue_type')
->add('tissue_subtype')
->add('sampling_date')
->add('cellularity')
->add('conservation')
->add('projects', 'entity', array('class' => 'Platform\ProjectBundle\Entity\Project'))
->add('description')
;
}
/**
* #param \Sonata\AdminBundle\Form\FormMapper $formMapper
*
* #return void
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('sample_name')
->add('individual')
->add('organ')
->add('organ_location')
->add('tissue_type')
->add('tissue_subtype')
->end()
->with('Miscelaneous')
->add('sampling_date')
->add('cellularity')
->add('conservation')
->end()
->with('Projects')
->add('projects')
->end()
->with('Description')
->add('description', 'sonata_type_model', array('multiple' => false))
->end()
;
}
/**
* #param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
*
* #return void
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('id')
->add('sample_name')
->add('individual')
->add('projects')
->add('organ')
->add('tissue')
->add('_action', 'actions', array(
'actions' => array(
'show' => array(),
'edit' => array(),
'delete' => array(),
)
))
;
}
/**
* #param \Sonata\AdminBundle\Datagrid\DatagridMapper $datagridMapper
*
* #return void
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('sample_name')
->add('individual')
->add('projects')
;
}
}
Here is the admin controller:
<?php
namespace Platform\ProjectBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Platform\ProjectBundle\Entity\Biosample;
class BiosampleAdminController extends Controller
{
}
And if you need it, here my composer.json:
{
"name": "symfony/framework-standard-edition",
"license": "MIT",
"type": "project",
"description": "The \"Symfony Standard Edition\" distribution",
"autoload": {
"psr-0": { "": "src/", "SymfonyStandard": "app/" }
},
"require": {
"php": ">=5.3.3",
"symfony/symfony": "2.6.*",
"doctrine/orm": "~2.2,>=2.2.3,<2.5",
"doctrine/dbal": "<2.5",
"doctrine/doctrine-bundle": "~1.2",
"twig/extensions": "~1.0",
"symfony/assetic-bundle": "~2.3",
"symfony/swiftmailer-bundle": "~2.3",
"symfony/monolog-bundle": "~2.4",
"sensio/distribution-bundle": "~3.0,>=3.0.12",
"sensio/framework-extra-bundle": "~3.0,>=3.0.2",
"jms/security-extra-bundle": "~1.2",
"ircmaxell/password-compat": "~1.0.3",
"stof/doctrine-extensions-bundle": "~1.1#dev",
"friendsofsymfony/user-bundle": "~1.3",
"incenteev/composer-parameter-handler": "~2.0",
"nervo/yuicompressor": "2.4.8",
"sonata-project/admin-bundle": "~2.3",
"sonata-project/doctrine-orm-admin-bundle": "~2.3",
"sonata-project/easy-extends-bundle": "~2.1",
"sonata-project/user-bundle": "~2.2",
"knplabs/knp-menu-bundle": "~1.1",
"mopa/bootstrap-bundle": "~2",
"twbs/bootstrap-sass": "~3.3.0",
"knplabs/knp-paginator-bundle": "dev-master",
"knplabs/knp-menu": "~1.1",
"craue/formflow-bundle": "~2.0"
},
"require-dev": {
"sensio/generator-bundle": "~2.3"
},
"scripts": {
"post-root-package-install": [
"SymfonyStandard\\Composer::hookRootPackageInstall"
],
"post-install-cmd": [
"Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles"
],
"post-update-cmd": [
"Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles"
]
},
"config": {
"bin-dir": "bin"
},
"extra": {
"symfony-app-dir": "app",
"symfony-web-dir": "web",
"symfony-assets-install": "relative",
"incenteev-parameters": {
"file": "app/config/parameters.yml"
},
"branch-alias": {
"dev-master": "2.6-dev"
}
}
}
Finally, here's my service declaration and my config.yml file:
Service.yml:
services:
platform.project.admin.biosample:
class: Platform\ProjectBundle\Controller\Admin\BiosampleAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: Project Manager, label: Biosample }
arguments: [null, Platform\ProjectBundle\Entity\Biosample, PlatformProjectBundle:BiosampleAdmin]
Config.yml:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
framework:
#esi: ~
translator: { fallbacks: ["%locale%"] }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
# handler_id set to null will use default session handler from php.ini
handler_id: ~
fragments: ~
http_method_override: true
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
# Assetic Configuration
assetic:
debug: "%kernel.debug%"
use_controller: false
bundles: [ ]
#java: /usr/bin/java
filters:
cssrewrite: ~
#closure:
# jar: "%kernel.root_dir%/Resources/java/compiler.jar"
#yui_css:
# jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar"
# Doctrine Configuration
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:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
# path: "%database_path%"
types:
json: Sonata\Doctrine\Types\JsonType
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: secured
user_class: Application\Sonata\UserBundle\Entity\User
group:
group_class: Application\Sonata\UserBundle\Entity\Group
group_manager: sonata.user.orm.group_manager
service:
user_manager: sonata.user.orm.user_manager
sonata_doctrine_orm_admin:
entity_manager: ~
sonata_block:
default_contexts: [cms]
blocks:
sonata.admin.block.admin_list:
contexts: [admin]
sonata.user.block.menu: ~
sonata.user.block.account: ~
sonata.block.service.text: ~
sonata_user:
security_acl: true
manager_type: orm
mopa_bootstrap:
form: ~
And last but not least: the full stack trace.
[1] ReflectionException: Class does not exist
at n/a
in /var/www/Project/app/cache/dev/classes.php line 6756
at ReflectionClass->__construct('')
in /var/www/Project/app/cache/dev/classes.php line 6756
at Doctrine\Common\Persistence\AbstractManagerRegistry->getManagerForClass(null)
in /var/www/Project/vendor/sonata-project/doctrine-orm-admin-bundle/Model/ModelManager.php line 220
at Sonata\DoctrineORMAdminBundle\Model\ModelManager->getEntityManager(null)
in /var/www/Project/vendor/sonata-project/doctrine-orm-admin-bundle/Model/ModelManager.php line 54
at Sonata\DoctrineORMAdminBundle\Model\ModelManager->getMetadata(null)
in /var/www/Project/vendor/sonata-project/doctrine-orm-admin-bundle/Model/ModelManager.php line 317
at Sonata\DoctrineORMAdminBundle\Model\ModelManager->getIdentifierFieldNames(null)
in /var/www/Project/app/cache/dev/classes.php line 12663
at Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList->__construct(object(ModelManager), null, null, null, null)
in /var/www/Project/app/cache/dev/classes.php line 13690
at Sonata\AdminBundle\Form\Type\ModelType->Sonata\AdminBundle\Form\Type\{closure}(object(OptionsResolver), object(SimpleChoiceList))
in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/OptionsResolver/OptionsResolver.php line 836
at Symfony\Component\OptionsResolver\OptionsResolver->offsetGet('choice_list')
in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/OptionsResolver/OptionsResolver.php line 769
at Symfony\Component\OptionsResolver\OptionsResolver->resolve(array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/ResolvedFormType.php line 109
at Symfony\Component\Form\ResolvedFormType->createBuilder(object(FormFactory), 'description', array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php line 82
at Symfony\Component\Form\Extension\DataCollector\Proxy\ResolvedTypeDataCollectorProxy->createBuilder(object(FormFactory), 'description', array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/FormFactory.php line 87
at Symfony\Component\Form\FormFactory->createNamedBuilder('description', 'sonata_type_model', null, array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/FormBuilder.php line 106
at Symfony\Component\Form\FormBuilder->create('description', 'sonata_type_model', array('sonata_field_description' => object(FieldDescription), 'class' => null, 'model_manager' => object(ModelManager), 'multiple' => false, 'label_render' => false, 'label' => 'Description'))
in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/FormBuilder.php line 268
at Symfony\Component\Form\FormBuilder->resolveChildren()
in /var/www/Project/vendor/symfony/symfony/src/Symfony/Component/Form/FormBuilder.php line 216
at Symfony\Component\Form\FormBuilder->getForm()
in /var/www/Project/app/cache/dev/classes.php line 9671
at Sonata\AdminBundle\Admin\Admin->buildForm()
in /var/www/Project/app/cache/dev/classes.php line 9930
at Sonata\AdminBundle\Admin\Admin->getForm()
in /var/www/Project/vendor/sonata-project/admin-bundle/Controller/CRUDController.php line 353
at Sonata\AdminBundle\Controller\CRUDController->editAction('1')
in line
at call_user_func_array(array(object(CRUDController), 'editAction'), array('1'))
in /var/www/Project/app/bootstrap.php.cache line 3022
at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
in /var/www/Project/app/bootstrap.php.cache line 2984
at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
in /var/www/Project/app/bootstrap.php.cache line 3133
at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request), '1', true)
in /var/www/Project/app/bootstrap.php.cache line 2377
at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
in /var/www/Project/web/app_dev.php line 28
Well, the reason for this error was a bad copy/paste from the tutorial.
In the Admin Class, the function configureFormFields contained a field "Description" badly described.
->with('Description')
->add('description', 'sonata_type_model', array('multiple' => false))
->end()
I had to replace it to:
->with('Description')
->add('description')
->end()
I discovered that automatic Admin Class skeleton generation was a function of Sonata Admin Bundle.
In order to automatically generate, execute:
php app/console sonata:admin:generate
Then enter the full path to your entity, in this example:
Platform\ProjectBundle\Entity\Biosample
The admin bundle will parse your entity and :
Generate the Admin Class file
Add an entry in your application bundle's service.yml
Generate optionnaly the CRUD controller
I guess this should be the prefered method when one is starting with sonata admin bundle.
I had the same problem, and for a reason i ignore, not in the past project where i've done exactly the same...
After an hour of search, i realize my table 'fos_user_user_group' has not been created has the mapping is not created. So my solution was simply to override the groups property of my entity User in order to define the Doctrine ORM Mapping :
/**
* The User can have many groups.
* #ORM\ManyToMany(targetEntity="Group")
* #ORM\JoinTable(name="fos_user_user_group",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;
After that, doctrine:schema:update --force and the problem was solved ;)
If you did it like me, and created first the database then via the console the yml files and from that the classes, then your annotations are useless.
Sonata is using yml and not annotations. They exist and seem to work but they just don't. To make the "Class does not exist" message go check what you yml definitions are saying. I needed to add the relationships and entity classes there.
If this is really the reason for your errors you might want to activate the annotations by deleting or moving the yml or xml templates somewhere else (..\Resources\config\doctrine).

Categories