Sonata Admin extending User admin class and not using generated bundle - symfony

I had some trouble extending user admin when i tried to use the classes in my bundle and not in the generated bundle (Application/Sonata/UserBundle).
I don't know if my solution is good but it works for me.
Here is the procedure:
First the config:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.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:
# 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%"
# added for sonata user
types:
json: Sonata\Doctrine\Types\JsonType
orm:
auto_generate_proxy_classes: "%kernel.debug%"
# added for sonata user
entity_managers:
default:
mappings:
SonataUserBundle: ~
FOSUserBundle: ~
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
# FosRest configuration
fos_rest:
view:
formats:
rss: false
xml: false
templating_formats:
html: true
force_redirects:
html: true
failed_validation: HTTP_BAD_REQUEST
default_engine: twig
# SonataAdmin configuration
sonata_block:
default_contexts: [cms]
blocks:
# Enable the SonataAdminBundle block
sonata.admin.block.admin_list:
contexts: [admin]
sonata.user.block.menu: # used to display the menu in profile pages
sonata.user.block.account: # used to display menu option (login option)
sonata_user:
security_acl: false
manager_type: orm # can be orm or mongodb
class:
user: Wf\Bundle\TestsBundle\Entity\User
group: Wf\Bundle\TestsBundle\Entity\Group
admin:
user:
class: Wf\Bundle\TestsBundle\Admin\UserAdmin
controller: SonataAdminBundle:CRUD
translation: SonataUserBundle
group:
class: Wf\Bundle\TestsBundle\Admin\GroupAdmin
controller: SonataAdminBundle:CRUD
translation: SonataUserBundle
fos_user:
db_driver: orm # can be orm or odm
firewall_name: main
user_class: Wf\Bundle\TestsBundle\Entity\User
# use this option when easy extending the bundle (app/console sonata:easy-extends:generate SonataUserBundle --dest=src)
#user_class: Sonata\UserBundle\Entity\BaseUser
group:
group_class: Wf\Bundle\TestsBundle\Entity\Group
#group_class: Sonata\UserBundle\Entity\BaseGroup
group_manager: sonata.user.orm.group_manager
service:
user_manager: sonata.user.orm.user_manager
UserAdmin class; same with GroupAdmin class
<?php
/**
* Created by razvan.
* Date: 1/16/15
* Time: 1:53 PM
*/
namespace Wf\Bundle\TestsBundle\Admin;
use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use FOS\UserBundle\Model\UserManagerInterface;
use Sonata\AdminBundle\Route\RouteCollection;
class UserAdmin extends BaseUserAdmin
{
/**
* {#inheritdoc}
*/
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->with('General')
->add('username')
->add('email')
->end()
// .. more fields
;
}
/**
* {#inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('User data')
->add('username')
->add('email')
->add('plainPassword', 'text', array('required' => false))
->end()
// .. more fields
;
if (!$this->getSubject()->hasRole('ROLE_SUPER_ADMIN')) {
$formMapper
->with('Management')
->add('roles', 'sonata_security_roles', array(
'expanded' => true,
'multiple' => true,
'required' => false
))
->add('locked', null, array('required' => false))
->add('expired', null, array('required' => false))
->add('enabled', null, array('required' => false))
->add('credentialsExpired', null, array('required' => false))
->end()
;
}
}
/**
* {#inheritdoc}
*/
protected function configureDatagridFilters(DatagridMapper $filterMapper)
{
$filterMapper
->add('id')
->add('username')
->add('locked')
->add('email')
;
}
/**
* {#inheritdoc}
*/
protected function configureListFields(ListMapper $listMapper)
{
// overide defaults
}
}
User class; same wirh Group class
<?php
namespace Wf\Bundle\TestsBundle\Entity;
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* Class User
* #package Wf\Bundle\TestsBundle\Entity
*
* #ORM\Table(name="fos_user_user")
* #ORM\Entity()
*/
class User extends BaseUser
{
/**
* #var integer $id
*
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/**
* Get id
*
* #return integer $id
*/
public function getId()
{
return $this->id;
}
}
Now in Resources\config create a folder named "doctrine" and then add the folowing files:
First file is named Group.orm.xml
Inser the following into the file
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="Wf\Bundle\TestsBundle\Entity\Group" table="fos_user_group">
<id name="id" column="id" type="integer">
<generator strategy="AUTO" />
</id>
</entity>
</doctrine-mapping>
Second file is User.orm.xml
Insert the following:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="Wf\Bundle\TestsBundle\Entity\User" table="fos_user_user">
<id name="id" column="id" type="integer">
<generator strategy="AUTO" />
</id>
</entity>
</doctrine-mapping>
Be careful to change the path to your own and clear the cache.

Related

Loggable doesn't write in the table

I want to use loogable extension, but it doesn't write anything in ext_log_enties table.
I'm using symfony 5.4 and Api-platform 2.6.8 in my project.
My configuration:
doctrine.yaml
doctrine:
dbal:
...
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
auto_mapping: true
mappings:
gedmo_loggable:
type: annotation
prefix: Gedmo\Loggable\Entity
dir: "%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Loggable/Entity"
alias: GedmoLoggable # (optional) it will default to the name set for the mapping
is_bundle: false
...
stof_doctrine_extensions.yaml
stof_doctrine_extensions:
default_locale: fr_FR
orm:
default:
...
loggable: true
User.php
#[Gedmo\Loggable]
class User implements UserInterface
{
/**
* #ORM\Column(type="string", length=128, nullable=false)
*/
#[Gedmo\Versioned]
private ?string $firstName = null;
/**
* #ORM\Column(type="string", length=128, nullable=false)
*/
#[Gedmo\Versioned]
private ?string $lastName = null;
}
service.yaml :
services:
...
gedmo.listener.loggable:
class: Gedmo\Loggable\LoggableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
What's wrong in my configuration ?

Edit Sonata User data

I'm trying to override Sonata User Admin class, on my bundle. For the moment, I just override the configureListFields method:
namespace App\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;
class UserAdmin extends BaseUserAdmin
{
/**
* #param ListMapper $listMapper
*/
protected function configureListFields(ListMapper $listMapper):void
{
$listMapper
->addIdentifier('username')
->add('email')
->add('groups')
->add('enabled', null, ['editable' => true])
->add('accountType')
->add('createdAt')
;
if ($this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
$listMapper
->add('impersonating', 'string', ['template' => '#SonataUser/Admin/Field/impersonating.html.twig'])
;
}
}
}
I refresh my page and I got the list of users without problem. But when I click into a user to edit it, I have this error: Call to a member function getClass() on null on these lines:
$now = new \DateTime();
$genderOptions = [
'choices' => \call_user_func([$this->getUserManager()->getClass(), 'getGenderList']),
'required' => true,
'translation_domain' => $this->getTranslationDomain(),
];
// NEXT_MAJOR: Remove this when dropping support for SF 2.8
if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) {
$genderOptions['choices_as_values'] = true;
}
Sonata_admin.yaml file:
sonata_admin:
title: 'Staff Admin Panel'
templates:
dashboard: '#SonataAdmin/Core/dashboard.html.twig'
security:
handler: sonata.admin.security.handler.role
role_admin: ROLE_ADMIN
role_super_admin: ROLE_SUPER_ADMIN
# information:
# GUEST: [VIEW, LIST]
# STAFF: [EDIT, LIST, CREATE]
# EDITOR: [OPERATOR, EXPORT]
# ADMIN: [MASTER]
# admin_permissions: [CREATE, LIST, DELETE, UNDELETE, EXPORT, OPERATOR, MASTER]
# object_permissions: [VIEW, EDIT, DELETE, UNDELETE, OPERATOR, MASTER, OWNER]
dashboard:
blocks:
- { type: sonata.admin.block.admin_list, position: left }
groups:
content:
label: Contenu
icon: '<i class="fa fa-file-text-o"></i>'
items:
- app.admin.specialty
- app.admin.cities
- app.admin.colleges
- app.admin.building
sonata.admin.group.media:
label: Médiathèque
icon: '<i class="fa fa-camera-retro"></i>'
items:
- sonata.media.admin.media
settings:
label: Paramètres
icon: '<i class="fa fa-cog"></i>'
items:
- sonata.classification.admin.category
- sonata.classification.admin.context
- sonata.classification.admin.tag
- sonata.classification.admin.collection
- app.admin.icon
sonata.admin.group.administration:
label: Utilisateur et Groupes
label_catalogue: SonataAdminBundle
icon: '<i class="fa fa-users"></i>'
items:
- app.admin.user
- sonata.user.admin.group
sonata_block:
blocks:
sonata.admin.block.admin_list:
contexts: [admin]
sonata_user:
security_acl: true
manager_type: orm
class:
user: App\Application\Sonata\UserBundle\Entity\User
group: App\Application\Sonata\UserBundle\Entity\Group
fos_user.yaml file:
fos_user:
db_driver: orm # valid values are 'orm', 'mongodb' and 'couchdb'
user_class: App\Entity\User #App\Application\Sonata\UserBundle\Entity\User
firewall_name: main
registration:
form:
type: App\Application\Sonata\UserBundle\Form\RegistrationType
group:
group_class: App\Application\Sonata\UserBundle\Entity\Group
group_manager: sonata.user.orm.group_manager
service:
user_manager: sonata.user.orm.user_manager
mailer: fos_user.mailer.noop
from_email:
address: "%env(MAILER_SENDER_ADDRESS)%"
sender_name: "%env(MAILER_SENDER_NAME)%"
If you want to access to your method getGenderList() from configureFormFields() you can do that :
protected function configureFormFields(FormMapper $formMapper)
{
$now = new \DateTime();
$genderOptions = [
'choices' => $this->getSubject()->getGenderList(), // here
'required' => true,
'translation_domain' => $this->getTranslationDomain(),
];
// NEXT_MAJOR: Remove this when dropping support for SF 2.8
if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) {
$genderOptions['choices_as_values'] = true;
}
}
See the Symfony docs about it.

cannot load Twig template (Symfony 2.8.8)

So I have the folder structure below:
According to the Symfony manual (click here), I should be able to load my Twig template but Symfony cannot find it.
Any ideas what I could be doing wrong? Thank you.
codes I've tried
return $this->render(
"AppBundle:DisplayForm.html.twig"
, array(
"form" => $form->createView()
);
return $this->render(
"DisplayForm.html.twig"
, array(
"form" => $form->createView()
)
);
Contents of my app/AppKernel.php
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'), true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
contents of app/config/config.yml
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
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: en
framework:
#esi: ~
#translator: { fallbacks: ["%locale%"] }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
templating:
engines: ['twig']
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%"
# 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%"
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 }
assetic:
debug: '%kernel.debug%'
use_controller: '%kernel.debug%'
filters:
cssrewrite: ~
Because you are storing the template inside the bundle, you also have to reference the directory within the views - in this case, a 'null' directory.
AppBundle::DisplayForm.html.twig
Note the :: for the directory.
If you moved the entire AppBundle/Resources/views/ directory to app/Resources/views/ then you would be able to reference them much as a plain subdirectory:
Referencing templates stored in:
app/Resources/views/ | AcmeDemoBundle/Resources/views
----------------------------- | -------------------------------
index.html.twig | AcmeDemoBundle::index.html.twig
Default/subdir/index.html.twig | AcmeDemoBundle:Default:subdir/index.html.twig
Default/subdir/index.html.twig | AcmeDemoBundle:Default/subdir:index.html.twig
Probably you have forgotten an # symbol:
return $this->render(
"#AppBundle/DisplayForm.html.twig", [
"form" => $form->createView(
]
);

Symfony 2.5.5 & FOSUserBundle: the class ... was not found in the chain configured namespaces

Recently, I started working with Symfony2. Now I want to add a user management engine to my site.
But I'm facing a problem. This is what I'm doing:
In terms of creating/installing a basic Symfony2 project:
$ composer create-project symfony/framework-standard-edition path/ "2.5.*"
$ mv path/* ./
$ rm -r path/
Ok, so much for Symfony 2.5.5. Next, download the FOSUserBundle and create a custom bundle:
$ composer require friendsofsymfony/user-bundle '~2.0#dev'
$ php app/console generate:bundle --namespace=Meiblorn/CoreBundle --format=yml
Create the User class in the Meiblorn\CoreBundle\Framework\Domain namespace
/**
* User: Meiblorn
* Date: 15/10/14
* Time: 20:17
*/
namespace Meiblorn\CoreBundle\Framework\Domain;
use FOS\UserBundle\Model\User as FOSUserBundleUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(
* name = "users"
* )
*/
class User extends FOSUserBundleUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct() {
parent::__construct();
// your own logic
}
}
?>
Configure the security.yml and config.yml. Finally, I got this:
AppKernel.php
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new FOS\UserBundle\FOSUserBundle(),
new Meiblorn\CoreBundle\MeiblornCoreBundle(),
);
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.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
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
firewall_name: prod
user_class: Meiblorn\CoreBundle\Framework\Domain\User
security.yml
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
prod:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
logout: true
anonymous: true
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
THIS IS THE PROBLEM
In browser: http://localhost/test.meiblorn.com/web/app_dev.php/
MappingException: The class 'Meiblorn\CoreBundle\Framework\Domain\User' was not found in the chain configured namespaces FOS\UserBundle\Model
in /Library/WebServer/Documents/test.meiblorn.com/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php line 37
at MappingException::classNotFoundInNamespaces('Meiblorn\CoreBundle\Framework\Domain\User', array('FOS\UserBundle\Model')) in /Library/WebServer/Documents/test.meiblorn.com/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php line 113
at MappingDriverChain->loadMetadataForClass('Meiblorn\CoreBundle\Framework\Domain\User', object(ClassMetadata)) in /Library/WebServer/Documents/test.meiblorn.com/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php line 117
at ClassMetadataFactory->doLoadMetadata(object(ClassMetadata), object(ClassMetadata), false, array()) in /Library/WebServer/Documents/test.meiblorn.com/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php line 318
Also Doctrine doesn't create tables for this mapping when calling doctrine:schema:update
Please, help me to fix this exception
UPDATE! How to fix
Final configuration for my namespace
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: false
mappings:
FOSUserBundle: ~
MeiblornCoreBundle:
type: annotation
dir: %kernel.root_dir%/../src/Meiblorn/CoreBundle/Framework/Entity
prefix: Meiblorn\CoreBundle\Framework\Entity
# alias: MyModels
# is_bundle: true
First you need to configure psr-4 autoload in your composer.js, for example
"autoload": {
"psr-4": {
"Meiblorn\\CoreBundle\\": "src/Meiblorn/CoreBundle/"
}
},
Then call composer dumpautoload.
Secondly, I believe Doctrine expects the entities to live in a folder Entity/, so try to move you model: src/Meiblorn/CoreBundle/Framework/Domain/User.php to src/Meiblorn/CoreBundle/Entity/User.php or How do I change symfony 2 doctrine mapper to use my custom directory instead of my Entity Directory under the bundle

How to install SonataDoctrineMongoDBAdminBundle properly?

I am really getting nervous because of lacking of enough resource for installing SonataDoctrineMongoDBAdminBundle and it's dependencies like sonataUserBundle. I have been trying to install this bundle for 15 days. I did everyting agaian and again what telling in sonata's official page. But it does not work properly. After extending sonataUserBundle as ApplicationUserBundle my final documents are:
User.php
<?php
/**
* This file is part of the <name> project.
*
* (c) <yourname> <youremail>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Application\Sonata\UserBundle\Document;
use Sonata\UserBundle\Document\BaseUser as BaseUser;
/**
* This file has been generated by the EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends )
*
* References :
* working with object : http://www.doctrine-project.org/docs/mongodb_odm/1.0/en/reference/working-with-objects.html
*
* #author <yourname> <youremail>
*/
class User extends BaseUser
{
/**
* #var integer $id
*/
protected $id;
/**
* Get id
*
* #return integer $id
*/
public function getId()
{
return $this->id;
}
}
Group.php
<?php
/**
* This file is part of the <name> project.
*
* (c) <yourname> <youremail>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Application\Sonata\UserBundle\Document;
use Sonata\UserBundle\Document\BaseGroup as BaseGroup;
/**
* This file has been generated by the EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends )
*
* References :
* working with object : http://www.doctrine-project.org/docs/mongodb_odm/1.0/en/reference/working-with-objects.html
*
* #author <yourname> <youremail>
*/
class Group extends BaseGroup
{
/**
* #var integer $id
*/
protected $id;
/**
* Get id
*
* #return integer $id
*/
public function getId()
{
return $this->id;
}
}
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
#esi: ~
translator: { fallback: %locale% }
secret: %secret%
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: %kernel.debug%
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
default_locale: "%locale%"
trusted_proxies: ~
session: ~
fragments: ~
# 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
# Swiftmailer Configuration
swiftmailer:
transport: %mailer_transport%
host: %mailer_host%
username: %mailer_user%
password: %mailer_password%
spool: { type: memory }
doctrine_mongodb:
connections:
default:
server: mongodb://localhost:27017
options: {}
default_database: test_database
document_managers:
default:
auto_mapping: true
# app/config/config.yml
sonata_block:
default_contexts: [cms]
blocks:
sonata.admin.block.admin_list:
contexts: [admin]
#sonata.admin_doctrine_orm.block.audit:
# contexts: [admin]
sonata.block.service.text:
sonata.block.service.rss:
# Some specific block from the SonataMediaBundle
#sonata.media.block.media:
#sonata.media.block.gallery:
#sonata.media.block.feature_media:
sonata_user:
security_acl: false
manager_type: mongodb # can be orm or mongodb
sonata_admin:
security:
handler: sonata.admin.security.handler.role
title: Sonatas Project
title_logo: /bundles/sonataadmin/logo_title.png
templates:
# default global templates
layout: SonataAdminBundle::standard_layout.html.twig
ajax: SonataAdminBundle::ajax_layout.html.twig
dashboard: SonataAdminBundle:Core:dashboard.html.twig
# default actions templates, should extend a global templates
list: SonataAdminBundle:CRUD:list.html.twig
show: SonataAdminBundle:CRUD:show.html.twig
edit: SonataAdminBundle:CRUD:edit.html.twig
dashboard:
blocks:
# display a dashboard block
- { position: left, type: sonata.admin.block.admin_list }
# Customize this part to add new block configuration
- { position: right, type: sonata.block.service.text, settings: { content: "<h2>Welcome to the Sonata Admin</h2> <p>This is a <code>sonata.block.service.text</code> from the Block Bundle, you can create and add new block in these area by configuring the <code>sonata_admin</code> section.</p> <br /> For instance, here a RSS feed parser (<code>sonata.block.service.rss</code>):"} }
- { position: right, type: sonata.block.service.rss, settings: { title: Sonata Project's Feeds, url: http://sonata-project.org/blog/archive.rss }}
# set to true to persist filter settings per admin module in the user's session
fos_user:
db_driver: mongodb # can be orm or odm
firewall_name: main
user_class: Application\Sonata\UserBundle\Document\User
group:
group_class: Application\Sonata\UserBundle\Document\Group
security.yml
jms_security_extra:
secure_all_services: false
expressions: true
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN]
ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
SONATA:
- ROLE_SONATA_PAGE_ADMIN_PAGE_EDIT # if you are using acl then this line must be commented
providers:
fos_userbundle:
id: fos_user.user_manager
firewalls:
# -> custom firewall for the admin area of the URL
admin:
switch_user: true
context: user
pattern: /admin(.*)
form_login:
provider: fos_userbundle
login_path: /admin/login
use_forward: false
check_path: /admin/login_check
failure_path: null
use_referer: true
logout:
path: /admin/logout
target: /admin/login
anonymous: true
# -> end custom configuration
# defaut login area for standard users
main:
switch_user: true
context: user
pattern: .*
form_login:
provider: fos_userbundle
login_path: /login
use_forward: false
check_path: /login_check
failure_path: null
logout: true
anonymous: true
access_control:
# URL of FOSUserBundle which need to be available to anonymous users
- { path: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/_profiler, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
# -> custom access control for the admin area of the URL
- { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/login-check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
# -> end
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
# Secured part of the site
# This config requires being logged for the whole site and having the admin role for the admin part.
# Change these rules to adapt them to your needs
- { path: ^/admin, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN] }
- { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
After all I run:
php app/console fos:user:create --super-admin
The task tells me the user created succesfully. Then I check my mongodb and there is only a record with 3 fields.
Here is the output:
> db.fos_user_user.findOne();
{
"_id" : 1,
"createdAt" : ISODate("2013-05-25T19:43:52Z"),
"updatedAt" : ISODate("2013-05-25T19:43:52Z"),
"gender" : "u"
}
As you see there is no a username or password or another field which pointed in sonata's or fos' document files. I installed SonataDoctrineORMAdminBundle to look if there is any problem with SonataAdminBundle but it works like a charm with mysql.
I am getting so crazy. Please tell me, what is the correct way to install sonataAdminBundle with mongoDB?
Thank you for your interest.
Seems that inheritance mapping is not working right, I followed the instructions but it lead to same problem. I got it fixed by changing reference to BaseUser to class provided by FOS\UserBundle
# Application\Sonata\UserBundle\Document\User.php
namespace Application\Sonata\UserBundle\Document;
//use Sonata\UserBundle\Document\BaseUser as BaseUser;
use FOS\UserBundle\Document\User as BaseUser;
I was also having issues with this, the users were created with just an ID, gender: 'u', createdAt, etc. And with this, I was able to make it work:
# app/config/config.yml
doctrine_mongodb:
connections:
default:
server: mongodb://localhost:27017
options: {}
default_database: test
document_managers:
default:
mappings:
ApplicationSonataUserBundle: ~
SonataUserBundle: ~
FOSUserBundle: ~
I hope someone find this useful.
I'm stucked at the same point.
I created user.php in a different folder with a different name, for my organization.
The difference was that I put direcly mongodb annotations
namespace myProject\BackEndBundle\Document;
use FOS\UserBundle\Document\User as BaseUser;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class BackEndUser extends BaseUser {
/**
* #MongoDB\Id
*/
protected $id;
/**
* Get id
*
* #return id $id
*/
public function getId()
{
return $this->id;
}
public function __construct()
{
parent::__construct();
// your own logic
}
}
Now user creation and authentication works, but user management in SonataAdminBundle don't works.

Resources