Attempted to load class "Media" from namespace "Application\MediaBundle\Entity" - php

I want to add a profile picture to my admin class, but i got this error :
Attempted to load class "Media" from namespace "Application\MediaBundle\Entity".
Did you forget a "use" statement for e.g. "Sonata\MediaBundle\Model\Media", "Sonata\MediaBundle\Tests\Entity\Media", "Sonata\MediaBundle\Tests\Document\Media" or "Sonata\MediaBundle\Tests\PHPCR\Media"?
I searched a lot but no solution.
this is my code
user entity
> /**
> * #var \Application\Sonata\MediaBundle\Entity\Media
> * #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media",
> cascade={"persist"}, fetch="LAZY")
> */
> protected $media;
>
> /**
> * Set media
> *
> * #param \Application\Sonata\MediaBundle\Entity\Media $media
> * #return User
> */
> public function setMedia(\Application\Sonata\MediaBundle\Entity\Media $media = null)
> {
> $this->media = $media;
>
> return $this;
> }
>
> /**
> * Get media
> *
> * #return \Application\Sonata\MediaBundle\Entity\Media
> */
> public function getMedia()
> {
> return $this->media;
> }
user admin
/**
* #param \Sonata\AdminBundle\Form\FormMapper $formMapper
*
* #return void
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('username')
->add('email')
->add('enabled')
->add('firstname')
->add('lastname')
->add('plainPassword', 'password', array(
'required' => (!$this->getSubject() || is_null($this->getSubject()->getId())),
))
->add('media', 'sonata_media_type', array('provider' => 'sonata.media.provider.image', 'context' => 'engine', 'data_class' => 'Application\Sonata\MediaBundle\Entity\Media', 'required' => false))
->end();
}
config.yml
# app/config/config.yml
sonata_media:
class:
media: Application\MediaBundle\Entity\Media
gallery: Application\MediaBundle\Entity\Gallery
gallery_has_media: Application\MediaBundle\Entity\GalleryHasMedia
# if you don't use default namespace configuration
#class:
# media: MyVendor\MediaBundle\Entity\Media
# gallery: MyVendor\MediaBundle\Entity\Gallery
# gallery_has_media: MyVendor\MediaBundle\Entity\GalleryHasMedia
db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr it is mandatory to choose one here
default_context: default # you need to set a context
contexts:
default: # the default context is mandatory
providers:
- sonata.media.provider.dailymotion
- sonata.media.provider.youtube
- sonata.media.provider.image
- sonata.media.provider.file
- sonata.media.provider.vimeo
formats:
small: { width: 100 , quality: 70}
big: { width: 500 , quality: 70}
# other contexts here
engine:
providers:
- sonata.media.provider.image
formats:
preview: { width: 100, quality: 100}
small: { width: 200, quality: 100}
large: { width: 600, quality: 100}
cdn:
server:
path: /uploads/media # http://media.sonata-project.org/
filesystem:
local:
directory: "%kernel.root_dir%/../web/uploads/media"
create: false
providers:
image:
resizer: sonata.media.resizer.square
doctrine:
orm:
entity_managers:
default:
mappings:
FOSUserBundle: ~
SonataMediaBundle: ~
dbal:
types: #this is about this line and line below
json: \Doctrine\DBAL\Types\StringType
doctrine_phpcr:
odm:
auto_mapping: true
mappings:
SonataMediaBundle:
prefix: Sonata\MediaBundle\PHPCR
this is the tutoruial
any help ?
sorry for the english

the problem is in the configuration file config.yml
> sonata_media:
> class:
> media: Application\Sonata\MediaBundle\Entity\Media
> gallery: Application\Sonata\MediaBundle\Entity\Gallery
> gallery_has_media: Application\Sonata\MediaBundle\Entity\GalleryHasMedia
> category: Application\Sonata\ClassificationBundle\Entity\Category

Related

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']

Sonata Media Bundle Template in Symfony 4

I have installed Sonata Media Bundle in Symfony 4 and all is correct, but something is different respect t Symfony 3.
I can't see the service in Sonata Admin and when I add the sonata media bundle field to an Admin Class this shows a different template.
Here images:
Sonata Media Bundle template - Symfony 4, in User Entity
Sonata Media Bundle template - Symfony 3, in User Entity
Sonata Media Bundle template - Symfony 3, Adding new image
As you can see the template is not working in Symfony 4 or I'm missing something in my code.
My Sonata Media config
sonata_media.yaml
sonata_media:
class:
media: App\Application\Sonata\MediaBundle\Entity\Media
gallery: App\Application\Sonata\MediaBundle\Entity\Gallery
gallery_has_media: App\Application\Sonata\MediaBundle\Entity\GalleryHasMedia
default_context: default
contexts:
default:
providers:
- sonata.media.provider.dailymotion
- sonata.media.provider.youtube
- sonata.media.provider.image
- sonata.media.provider.file
- sonata.media.provider.vimeo
formats:
small: { width: 100 , quality: 70}
big: { width: 500 , quality: 70}
cdn:
server:
path: /upload/media
filesystem:
local:
# Directory for uploads should be writable
directory: "%kernel.project_dir%/public/upload/media"
create: false
providers:
# ...
file:
# the resizer must be set to false, otherwhise this can delete icon files from the fs
resizer: false
image:
thumbnail: sonata.media.thumbnail.format # default value
# thumbnail: sonata.media.thumbnail.consumer.format # can be used to dispatch the resize action to async task
# thumbnail: sonata.media.thumbnail.liip_imagine # use the LiipImagineBundle to resize the image
vimeo:
thumbnail: sonata.media.thumbnail.format # default value
# thumbnail: sonata.media.thumbnail.consumer.format # can be used to dispatch the resize action to async task
# thumbnail: sonata.media.thumbnail.liip_imagine # use the LiipImagineBundle to resize the image
youtube:
thumbnail: sonata.media.thumbnail.format # default value
# thumbnail: sonata.media.thumbnail.consumer.format # can be used to dispatch the resize action to async task
# thumbnail: sonata.media.thumbnail.liip_imagine # use the LiipImagineBundle to resize the image
dailymotion:
thumbnail: sonata.media.thumbnail.format # default value
# thumbnail: sonata.media.thumbnail.consumer.format # can be used to dispatch the resize action to async task
# thumbnail: sonata.media.thumbnail.liip_imagine # use the LiipImagineBundle to resize the image
My User's Admin Class
// src/Admin/OgaUsersAdmin.php
namespace App\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\MediaBundle\Form\Type\MediaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class OgaUsersAdmin extends AbstractAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('userFirstName', TextType::class)
->add('userCollection', MediaType::class, array(
'provider' => 'sonata.media.provider.image',
'context' => 'default'
));
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper->add('userFirstName');
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper->addIdentifier('userFirstName');
}
}
My Users Entity and Media Bundle field
namespace App\Entity;
use Application\Sonata\MediaBundle\Entity\Media;
use Doctrine\ORM\Mapping as ORM;
/**
* OgaUsers
*
* #ORM\Table(name="oga_users", indexes={#ORM\Index(name="memb_id_idx", columns={"memb_id"}), #ORM\Index(name="comp_id_idx", columns={"comp_id"}), #ORM\Index(name="u_ui_id_idx", columns={"user_collection"})})
* #ORM\Entity
*/
class OgaUsers
{
/**
* #var int
*
* #ORM\Column(name="user_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $userId;
/**
* #var Media
*
* #ORM\ManyToOne(targetEntity="App\Application\Sonata\MediaBundle\Entity\Media")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="userCollection", referencedColumnName="id")
* })
*/
private $userCollection;
Getter and Settter
public function getUserCollection(): ?\App\Application\Sonata\MediaBundle\Entity\Media
{
return $this->userCollection;
}
public function setUserCollection(?\App\Application\Sonata\MediaBundle\Entity\Media $userCollection): self
{
$this->userCollection = $userCollection;
return $this;
}
Thank's
After search for some weeks.
I have the answer.
First I need to add this line to my sonata_media.yaml, to see the Media Library in Admin Dashboard.
db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr it is mandatory to choose one here
After in Admin in configureFormFields, just need to add ModellistType::class, to the media field.
class OgaUsersAdmin extends AbstractAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('userFirstname', TextType::class)
->add('userImage', ModelListType::class);
}
Hope it helps!!

Vich and gaufrette are not saving files in sonata admin

I'm trying to make an upload linked to an entity in Sonata Admin using Vich.
All the configuration is done but the file does not upload, and I cannot find the error.
The problem is that when y try to upload the file, every thing seem to work fine, Sonata persists the data in all the data base fields, and the file is uploaded to /tmp folder in teh sistem,also, sonata prints the tmp route in the patch field in database. But the file never gets to the folder setted in gaufrette and neither generates the unique name.
Here is the code:
The admin Class:
<?php
namespace DownloadFileAdminBundle\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
class DownloadFileAdmin extends Admin
{
const FILE_MAX_SIZE = 2 * 1024 * 1024; // 2 megas
/**
* #param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$fileOptions = array(
'label' => 'Archivo',
'required' => true,
'vich_file_object' => 'downloadfile',
'vich_file_property' => 'downloadFile',
'vich_allow_delete' => true,
'attr' => array(
'data-max-size' => self::FILE_MAX_SIZE,
'data-max-size-error' => 'El tamaño del archivo no puede ser mayor de 2 megas'
)
);
$formMapper
->add('slug', null, array('label' => 'Slug'))
->add('title', null, array('label' => 'Título'))
->add('description', null, array('label' => 'Descripción'))
->add('roles')
->add('path', 'DownloadFileAdminBundle\Form\Extension\VichFileObjectType', $fileOptions)
;
}
/**
* #param ListMapper $listMapper
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
->add('slug')
->add('title')
->add('description')
->add('path')
->add('roles')
->add('_action', null, array(
'actions' => array(
'show' => array(),
'edit' => array(),
'delete' => array(),
)
))
;
}
}
Here is the entity, with the not persistent fieln and the path field, witch is wher eI want tostore the file path:
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
* #Vich\UploadableField(mapping="download_file", fileNameProperty="path")
* #var File
*/
private $downloadFile;
/**
* #ORM\Column(type="string")
*/
protected $path;
public function getDownloadFile()
{
return $this->downloadFile;
}
/**
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $file
*
* #return File
*/
public function setDownloadFile(File $file = null)
{
$this->downloadFile = $file;
return $this;
}
/**
* #return mixed
*/
public function getPath()
{
return $this->path;
}
/**
* #param mixed $path
*/
public function setPath($path)
{
$this->path = $path;
}
The services os admin.yml
services:
sonata.admin.file:
class: DownloadFileAdminBundle\Admin\DownloadFileAdmin
arguments: [~, Opos\DownloadFileBundle\Entity\DownloadFile, SonataAdminBundle:CRUD]
tags:
- { name: sonata.admin, manager_type: orm, group: "Files", label: "Archivo" }
and services.yml:
services:
download_file_admin_bundle.vich_file_object_type:
class: DownloadFileAdminBundle\Form\Extension\VichFileObjectType
arguments: [ "#doctrine.orm.entity_manager" ]
tags:
- { name: "form.type", alias: "vich_file_object" }
And last vich and gaufrette configuration:
vich_uploader:
db_driver: orm
storage: gaufrette
mappings:
question_image:
uri_prefix: ~
upload_destination: questions_image_fs
namer: vich_uploader.namer_uniqid
download_file:
uri_prefix: ~
upload_destination: download_file_fs
namer: vich_uploader.namer_uniqid
knp_gaufrette:
stream_wrapper: ~
adapters:
questions_image_adapter:
local:
directory: %kernel.root_dir%/../web/images/questions
download_file_adapter:
local:
directory: %kernel.root_dir%/../web/files/download
filesystems:
questions_image_fs:
adapter: questions_image_adapter
download_file_fs:
adapter: download_file_adapter
VichUploaderBundle relies on Doctrine Events like pre persist/update to trgger its upload functionality. When you open existing entity in the admin section and upload new file without changing anything else, doctrine wouldn't dispatch lifecycle events as none of doctrine specific fields are changed.
So whenever new file object passed to the entity you need to update some doctrine specific field value, like updatedAt. Modify setDownloadFile of the entity to:
/**
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $file
*
* #return File
*/
public function setDownloadFile(File $file = null)
{
$this->downloadFile = $file;
if ($file) {
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
Also you need to add updatedAt field and it's mapping in case you didnt.
Take a look at the example on VichUploaderBundle documentation page: https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/usage.md#step-2-link-the-upload-mapping-to-an-entity
UPDATE
Also you need to define form field on downloadFile property instead of path

No entity manager defined for class

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**: ~

Sonata Missing argument

I have this Error when i'm trying to access my site with a fresh installation of sonata adminBUndle. I can see the list i can see the dashboard but if i try to add a post I got this message.
Missing argument 1 for Sonata\AdminBundle\Admin\Admin::__construct(),
called in
C:\wamp\www\sonata\vendor\sonata-project\doctrine-orm-admin-bundle\Sonata\DoctrineORMAdminBundle\Model\ModelManager.php on line 416 and defined in
C:\wamp\www\sonata\app\cache\dev\classes.php line 8120
anybody can help????
Ok thx for you're answer there is the code
Symfony 2.4.1
the entity
<?php
namespace Tic\ClasseBundle\Entity;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Doctrine\ORM\Mapping as ORM;
/**
* Groupe
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Tic\ClasseBundle\Entity\GroupeRepository")
*/
class Groupe extends Admin
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="groupe", type="string", length=255)
*/
private $groupe;
/**
* #var string
*
* #ORM\Column(name="enseignant", type="string", length=255)
*/
private $enseignant;
/**
* #var string
*
* #ORM\Column(name="grepere", type="string", length=255)
*/
private $grepere;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set groupe
*
* #param string $groupe
* #return Groupe
*/
public function setGroupe($groupe)
{
$this->groupe = $groupe;
return $this;
}
/**
* Get groupe
*
* #return string
*/
public function getGroupe()
{
return $this->groupe;
}
/**
* Set enseignant
*
* #param string $enseignant
* #return Groupe
*/
public function setEnseignant($enseignant)
{
$this->enseignant = $enseignant;
return $this;
}
/**
* Get enseignant
*
* #return string
*/
public function getEnseignant()
{
return $this->enseignant;
}
/**
* Set grepere
*
* #param string $grepere
* #return Groupe
*/
public function setGrepere($grepere)
{
$this->grepere = $grepere;
return $this;
}
/**
* Get grepere
*
* #return string
*/
public function getGrepere()
{
return $this->grepere;
}
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('enseignant', 'text',array('label'=>'Enseignants(es)'))
->add('groupe', 'text',array('label'=>'Groupe'))
->add('grepere', 'text',array('label'=>'Groupe Repere')) //if no type is specified, SonataAdminBundle tries to guess it
;
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('enseignant')
->add('grepere')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('enseignant')
->add('grepere')
->add('groupe')
;
}
}
the config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: #TicClasseBundle/Resources/config/admin.yml }
framework:
#esi: ~
translator: { fallback: "%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, add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
sonata_admin:
title: Gestion de classe
sonata_block:
default_contexts: [cms]
blocks:
# Enable the SonataAdminBundle block
sonata.admin.block.admin_list:
contexts: [admin]
# Your other blocks
sonata_doctrine_orm_admin:
# default value is null, so doctrine uses the value defined in the configuration
entity_manager: ~
templates:
form:
- SonataDoctrineORMAdminBundle:Form:form_admin_fields.html.twig
filter:
- SonataDoctrineORMAdminBundle:Form:filter_admin_fields.html.twig
types:
list:
array: SonataAdminBundle:CRUD:list_array.html.twig
boolean: SonataAdminBundle:CRUD:list_boolean.html.twig
date: SonataAdminBundle:CRUD:list_date.html.twig
time: SonataAdminBundle:CRUD:list_time.html.twig
datetime: SonataAdminBundle:CRUD:list_datetime.html.twig
text: SonataAdminBundle:CRUD:base_list_field.html.twig
trans: SonataAdminBundle:CRUD:list_trans.html.twig
string: SonataAdminBundle:CRUD:base_list_field.html.twig
smallint: SonataAdminBundle:CRUD:base_list_field.html.twig
bigint: SonataAdminBundle:CRUD:base_list_field.html.twig
integer: SonataAdminBundle:CRUD:base_list_field.html.twig
decimal: SonataAdminBundle:CRUD:base_list_field.html.twig
identifier: SonataAdminBundle:CRUD:base_list_field.html.twig
currency: SonataAdminBundle:CRUD:list_currency.html.twig
percent: SonataAdminBundle:CRUD:list_percent.html.twig
choice: SonataAdminBundle:CRUD:list_choice.html.twig
url: SonataAdminBundle:CRUD:list_url.html.twig
show:
array: SonataAdminBundle:CRUD:show_array.html.twig
boolean: SonataAdminBundle:CRUD:show_boolean.html.twig
date: SonataAdminBundle:CRUD:show_date.html.twig
time: SonataAdminBundle:CRUD:show_time.html.twig
datetime: SonataAdminBundle:CRUD:show_datetime.html.twig
text: SonataAdminBundle:CRUD:base_show_field.html.twig
trans: SonataAdminBundle:CRUD:show_trans.html.twig
string: SonataAdminBundle:CRUD:base_show_field.html.twig
smallint: SonataAdminBundle:CRUD:base_show_field.html.twig
bigint: SonataAdminBundle:CRUD:base_show_field.html.twig
integer: SonataAdminBundle:CRUD:base_show_field.html.twig
decimal: SonataAdminBundle:CRUD:base_show_field.html.twig
currency: SonataAdminBundle:CRUD:base_currency.html.twig
percent: SonataAdminBundle:CRUD:base_percent.html.twig
choice: SonataAdminBundle:CRUD:show_choice.html.twig
url: SonataAdminBundle:CRUD:show_url.html.twig
and the admin.yml
services:
sonata.admin.post:
class: Tic\ClasseBundle\Entity\Groupe
tags:
- { name: sonata.admin, manager_type: orm, group: "Gestion de classe", label: "Groupe" }
arguments:
- ~
- Tic\ClasseBundle\Entity\Groupe
- ~
calls:
- [ setTranslationDomain, [AcmeDemoBundle]]
thax
Your entity class Groupe is incorrect.
It will not extend Sonata admin class.
Methods configureListFields, configureFormFields, configureDatagridFilters should not be here. They must be in separate admin class(an analog symfony controller class)
Example:
<?php
namespace Tic\ClasseBundle\Controller\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class GroupeAdmin extends Admin
{
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('id')
->addIdentifier('name')
->add('country');
}
protected function configureFormFields(FormMapper $form)
{
$form
->add('id', null, [
'attr' => [
'readonly' => true,
],
])
->add('name')
->add('country');
}
protected function configureDatagridFilters(DatagridMapper $filter)
{
$filter
->add('id')
->add('name')
->add('country');
}
}
The entity and admin page should be separated from each other. Your entity shouldn't extend the Admin class Sonata provides, but you should create a new file instead which extend the Admin class.
sonata.admin.post:
class: Tic\ClasseBundle\Admin\AdminGroupe /*Locating the admin file*/
tags:
- { name: sonata.admin, manager_type: orm, group: "Gestion de classe", label: "Groupe" }
arguments:
- ~
- Tic\ClasseBundle\Entity\Groupe
- ~
calls:
- [ setTranslationDomain, [AcmeDemoBundle]]
I highly suggest to read the documentation (again) Sonata provides see: https://sonata-project.org/bundles/admin/3-x/doc/getting_started/creating_an_admin.html

Categories