I'm using the Sylius Cart and Order Bundles and trying to add an item to the cart and show a summary of the items in the cart. The problem I'm having is Symfony/Sylius forgets that it has made a cart and added items to it.
If I click a link going to the add page for the sylius cart, generated by
{{ path('sylius_cart_item_add', {'productId': class.ClassID}) }}
No error occurs. If I look in the database I can see that a new entry has been created in the sylius_cart table and the sylius_cart_item table, with the correct information; however, the cart summary page shows nothing and thinks the cart is empty.
If I try to add another item, it creates another new cart and promptly forgets that it made the cart.
I have the following bundles loading in AppKernel.php
public function registerBundles()
{
$bundles = array(
//bundles for using the shopping cart
new FOS\RestBundle\FOSRestBundle(),
new JMS\SerializerBundle\JMSSerializerBundle($this),
new Sylius\Bundle\ResourceBundle\SyliusResourceBundle(),
new WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle(),
new Sylius\Bundle\MoneyBundle\SyliusMoneyBundle(),
new Sylius\Bundle\OrderBundle\SyliusOrderBundle(),
new Sylius\Bundle\CartBundle\SyliusCartBundle(),
new Sylius\Bundle\SequenceBundle\SyliusSequenceBundle(),
//bundles for styling with bootstrap 3
new Mopa\Bundle\BootstrapBundle\MopaBootstrapBundle(),
//mssql connection library
new Realestate\MssqlBundle\RealestateMssqlBundle(),
//default frameworks
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 Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new CE\CEBundle\CEBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
My ItemResolver class looks like
namespace CE\CEBundle\Cart;
use Sylius\Component\Cart\Model\CartItemInterface;
use Sylius\Component\Cart\Resolver\ItemResolverInterface;
use Sylius\Component\Cart\Resolver\ItemResolvingException;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
class ItemResolver implements ItemResolverInterface
{
private $entityManager;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function resolve(CartItemInterface $item, $data)
{
//grab the product ID
$productId = $data->get('productId');
if (!$productId || !$product = $this->getProductRepository()->find($productId)) {
throw new ItemResolvingException('Requested product was not found');
}
$item->setProductId($product->getId());
$item->setUnitPrice($product->getClassFee() * 100);
return $item;
}
private function getProductRepository()
{
return $this->entityManager->getRepository('CEBundle:Product');
}
}
My CartItem class looks like
namespace CE\CEBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Sylius\Component\Cart\Model\CartItem as BaseCartItem;
/**
* #ORM\Entity
* #ORM\Table(name="sylius_cart_item")
*/
class CartItem extends BaseCartItem
{
/**
* #ORM\Column(type="string", name="product_id", length=8)
*/
private $productId;
public function getProductId()
{
return $this->productId;
}
public function setProductId($Id)
{
$this->productId = $Id;
}
}
I have the following config in my 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: ~
name: SYLIUS_SESSION
cookie_lifetime: 72000
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:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
mssqlDB:
driver_class: Realestate\MssqlBundle\Driver\PDODblib\Driver
host: %db.other.host%
dbname: %db.other.db_name%
user: %db.other.user%
password: %db.other.password%
# 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:
default_entity_manager: default
entity_managers:
default:
connection: default
mappings:
CEBundle: ~
mssqlDB:
connection: mssqlDB
mappings:
CEBundle: ~
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 }
#sylius configuration
sylius_cart:
resolver: ce.cart_item_resolver
classes: ~
provider: sylius.cart_provider.default
storage: sylius.storage.session
sylius_order:
driver: doctrine/orm
classes:
order_item:
model: CE\CEBundle\Entity\CartItem
sylius_sequence:
driver: doctrine/orm
#mopa configuration for forms and bootstrap
mopa_bootstrap:
form:
checkbox_label: 'widget'
Of note, if I watch the Resources tab in the Chrome Developer Tools, I can see that SYLIUS_SESSION does get set when I add an item to the cart.
I've tried changing the storage to cookie instead of session and pouring over the documents, but I'm at a loss as to what to do to fix this. My guess is it's probably something small, I just don't know what it is.
Thank you for any help in advance.
In your config.yml file you are using sylius.cart_provider.default which means that you need to get the current Sylius Cart Provider before adding an item to it.
So that means in your controller, you will need to retrieve the cart_provider service like so:
// gets the current cart
$cart = $this->get('sylius.cart_provider')->getCart();
After that, you can create an $item like you are doing in the call to the ItemResolver::resolve() method and the item can be added to the cart.
You may also need to add the dispatcher events for the cart ITEM_ADD_INITIALIZE, CART_CHANGE, etc to your code to actually have the items appear in the cart.
Have a look at the CartItemEvent class for that. If you need help with that let me know.
Related
I am trying to flush in symfony with MongoDB and when i do :
$dm = $this->get('doctrine_mongodb')->getManager();
I have this error when i do the command :
Service "doctrine_mongodb" not found: even though it exists in the app's container, the container inside "AppBundle\Controller\api\MessageUserController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "session" and "twig" services. Unless you need extra laziness, try using dependency injection instead. Otherwise, you need to declare it using "MessageUserController::getSubscribedServices()".
There is my 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
parameters:
locale: en
image_directory: '%kernel.project_dir%/web/uploads/images'
framework:
#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:
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_3_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:
request: { converters: true }
fos_rest:
view:
formats: { json: true, xml: false, rss: false }
view_response_listener: true
mime_types:
json: ['application/json', 'application/json;version=1.0',
'application/json;version=2.0']
serializer:
serialize_null: true
body_converter:
enabled: true
validate: true
validation_errors_argument: violations
#format_listener:
# rules:
# - { path: 'api/', priorities: ['json'], fallback_format:
'json' }
exception:
enabled: true
codes:
{ AppBundle\Exception\ResourceValidationException: 400 }
exception_controller: 'fos_rest.exception.controller:showAction'
versioning:
enabled: true
resolvers:
media_type: # Accept header
enabled: true
regex: '/(v|version)=(?P<version>[0-9\.]+)/'
lexik_jwt_authentication:
private_key_path: '%jwt_private_key_path%'
public_key_path: '%jwt_public_key_path%'
pass_phrase: '%jwt_key_pass_phrase%'
doctrine_mongodb:
connections:
default:
server: "%mongodb_server%"
options: {}
default_database: Boojon_db
document_managers:
default:
auto_mapping: true
My controller :
namespace AppBundle\Controller\api;
use AppBundle\Document\MessageUser;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use FOS\RestBundle\Controller\Annotations as Rest;
/**
* #Security("is_anonymous() or is_authenticated()")
* #Route("api")
*/
class MessageUserController extends AbstractController
{
/**
*
* #Rest\Post(
* path = "/message/user/add",
* name = "api_message_add"
* )
* #Rest\View(StatusCode=201)
*/
public function UserAddMessageAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$content = ($request->get('content'));
$user = $em->getRepository('AppBundle:User')->findOneBy(array('id'
=> ($request->get('id_user'))));
$token = $request->get('token');
$friend = $em->getRepository('AppBundle:User')-
>findOneBy(array('id' => ($request->get('id_friend'))));
if (!isset($content) ) {
return new JsonResponse([
'success' => "false",
'message' => "Message non renseigné"
]);
}
if (!isset($token)) {
return new JsonResponse([
'success' => "false",
'message' => "Token non renseigné"
]);
}
if ($user->getToken() != $token) {
return new JsonResponse([
'success' => "false",
'message' => "Bad token",
]);
}
if (!isset($friend) or !isset($user)) {
return new JsonResponse([
'success' => "false",
'message' => "Message sans propriétaire ou destinataire"
]);
}
$message = new MessageUser();
$message->setRead('0');
$message->setIdReceiver($friend->getId());
$message->setIdTransmitter($user->getId());
$message->setSendAt(new \DateTime('now'));
$message->setContent($content);
$dm = $this->get('doctrine_mongodb')->getManager();
$dm->persist($message);
$dm->flush();
return new JsonResponse([
'success' => "true",
'message' => "Message ajouté"
]);
}
}
Thx for all that will try to answer :)
AbstractController is a simpler base controller, it has no full container support, your options are:
Inject doctrine_mongodb/manager service directly trough constructor/method argument.
or
Extend from Symfony\Bundle\FrameworkBundle\Controller instead of Symfony\Bundle\FrameworkBundle\Controller\AbstractController
(Using WampServer on Windows 10.)
I followed the official documentation in order to install Sonata User Bundle over Symfony.
I get the following error message
(1/1) ClassNotFoundException Attempted to load class "FOSUserBundle"
from namespace "FOS\UserBundle". Did you forget a "use" statement for
another namespace?
AppKernel.php
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
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 Sonata\CoreBundle\SonataCoreBundle(),
//Added following https://sonata-project.org/bundles/admin/3-x/doc/getting_started/installation.html
new Sonata\BlockBundle\SonataBlockBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
new Sonata\AdminBundle\SonataAdminBundle(),
//Added following https://sonata-project.org/bundles/easy-extends/2-x/doc/reference/installation.html
new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
//Added following https://sonata-project.org/bundles/user/3-x/doc/reference/installation.html
new FOS\UserBundle\FOSUserBundle(),
new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
if ('dev' === $this->getEnvironment()) {
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
$bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
}
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
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
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: en
framework:
#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 }
templating:
engines: ['twig']
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%'
# 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%'
types:
json: Sonata\Doctrine\Types\JsonType
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
entity_managers:
default:
mappings:
ApplicationSonataUserBundle: ~
SonataUserBundle: ~
FOSUserBundle: ~ # If SonataUserBundle extends it
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
#Sonata
sonata_core:
form_type: horizontal
sonata_user:
security_acl: true
manager_type: orm # can be orm or mongodb
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.block.service.text: # used to if you plan to use Sonata user routes
#FOSUser
fos_user:
db_driver: orm # can be orm or odm
firewall_name: main
user_class: Sonata\UserBundle\Entity\BaseUser
group:
group_class: Sonata\UserBundle\Entity\BaseGroup
group_manager: sonata.user.orm.group_manager # If you're using doctrine orm (use sonata.user.mongodb.group_manager for mongodb)
service:
user_manager: sonata.user.orm.user_manager # If you're using doctrine orm (use sonata.user.mongodb.user_manager for mongodb)
routing.yml
login_view:
path: '/login/'
defaults: { _controller: AppBundle:Login:view }
singlesingon_view:
path: '/authentication/singlesignon/'
defaults: { _controller: AppBundle:AuthenticationSingleSignOn:view }
singlesingout_view:
path: '/authentication/singlesignout/'
defaults: { _controller: AppBundle:AuthenticationSingleSignOut:view }
app:
resource: '#AppBundle/Controller/'
type: annotation
admin_area:
resource: "#SonataAdminBundle/Resources/config/routing/sonata_admin.xml"
prefix: /admin
sonata_user_admin_security:
resource: '#SonataUserBundle/Resources/config/routing/admin_security.xml'
prefix: /admin
sonata_user_admin_resetting:
resource: '#SonataUserBundle/Resources/config/routing/admin_resetting.xml'
prefix: /admin/resetting
When I reach step 2.5 which starts with running
php bin/console sonata:easy-extends:generate SonataUserBundle -d src
I get
Fatal error: Class 'FOS\UserBundle\FOSUserBundle' not found.
As requested in comments: autoload section of composer.json
"autoload": {
"psr-4": {
"AppBundle\\": "src/AppBundle"
},
"classmap": [ "app/AppKernel.php", "app/AppCache.php" ]
},
In composer.json
"autoload": {
"psr-0": {
"": "src/",
"Application": "app/"
}
},
than Update Composer :
composer update
if this dont work so try to fix the bundle by this command :
php app/console sonata:easy-extends:generate --dest=src SonataMediaBundle
Extend base user FosUser :
class Myusers extends BaseUser
{
}
In config.yml
fos_user:
user_class: MyBundle\Entity\Myusers
Trying to use KnpPaginatorBundle and WhiteOctoberPagerfantaBundle
If i have url
/categories/tech/plates
next page url show me
/catalog/categories/tech/plates?/catalog/categories/tech/plates=&page=2
I can not understand why this is happening :(
Can anyone help?
What am I doing wrong?
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
// default symfony project
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 Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
// additional
// new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(),
new SimpleThings\EntityAudit\SimpleThingsEntityAuditBundle(),
new Sonata\IntlBundle\SonataIntlBundle(),
new FOS\JsRoutingBundle\FOSJsRoutingBundle(),
new A2lix\TranslationFormBundle\A2lixTranslationFormBundle(),
new WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle(),
new Bazinga\Bundle\JsTranslationBundle\BazingaJsTranslationBundle(),
// admin panel
new Sonata\CoreBundle\SonataCoreBundle(),
new Sonata\BlockBundle\SonataBlockBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
new Sonata\AdminBundle\SonataAdminBundle(),
new Application\Sonata\AdminBundle\ApplicationSonataAdminBundle(),
new Sonata\MediaBundle\SonataMediaBundle(),
new CoopTilleuls\Bundle\CKEditorSonataMediaBundle\CoopTilleulsCKEditorSonataMediaBundle(),
new Application\Sonata\MediaBundle\ApplicationSonataMediaBundle(),
// // users
new FOS\UserBundle\FOSUserBundle(),
new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
new FOS\OAuthServerBundle\FOSOAuthServerBundle(),
new Application\FOS\OAuthServerBundle\ApplicationFOSOAuthServerBundle(),
// new HWI\Bundle\OAuthBundle\HWIOAuthBundle(),
// new Xxx\Bundle\OAuthUserBundle\XxxOAuthUserBundle(),
// rest api default
new FOS\RestBundle\FOSRestBundle(),
new JMS\SerializerBundle\JMSSerializerBundle(),
new Nelmio\ApiDocBundle\NelmioApiDocBundle(),
new Application\FOS\RestBundle\ApplicationFOSRestBundle(),
// form
new Ivory\OrderedFormBundle\IvoryOrderedFormBundle(), //order fields with 'position' attribute
//form types
new Genemu\Bundle\FormBundle\GenemuFormBundle(),
new Stnw\DatePickerBundle\StnwDatePickerBundle(),
new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
new Misd\PhoneNumberBundle\MisdPhoneNumberBundle(),
// charts
// new Ob\HighchartsBundle\ObHighchartsBundle(),
// grid
new APY\DataGridBundle\APYDataGridBundle(),
// new Lunetics\LocaleBundle\LuneticsLocaleBundle(),
new JMS\I18nRoutingBundle\JMSI18nRoutingBundle(),
new JMS\TranslationBundle\JMSTranslationBundle(),
// project
new Xxx\Bundle\AppBundle\XxxAppBundle(),
new Xxx\Bundle\CompanyBundle\XxxCompanyBundle(),
new Xxx\Bundle\TransactionBundle\XxxTransactionBundle(),
new Xxx\Bundle\StoreBundle\XxxStoreBundle(),
new Xxx\Bundle\DeviceBundle\XxxDeviceBundle(),
new Xxx\Bundle\CatalogBundle\XxxCatalogBundle(),
new Xxx\Bundle\ChipBundle\XxxChipBundle(),
new Xxx\Bundle\CityBundle\XxxCityBundle(),
new Xxx\Bundle\LastActivityBundle\XxxLastActivityBundle(),
// frontend
new WhiteOctober\BreadcrumbsBundle\WhiteOctoberBreadcrumbsBundle(),
new Xxx\ContactBundle\XxxContactBundle(),
new Application\Xxx\ContactBundle\ApplicationXxxContactBundle(),
new Xxx\Bundle\FaqBundle\XxxFaqBundle(),
new Xxx\Bundle\NewsBundle\XxxNewsBundle(),
new Xxx\Bundle\MenuBundle\XxxMenuBundle(),
new Xxx\Bundle\PageBundle\XxxPageBundle(),
new Xxx\Bundle\SmsGatewayBundle\XxxSmsGatewayBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'])) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
// translator, needed for grid
$bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
// $bundles[] = new JMS\TranslationBundle\JMSTranslationBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
# app/config/config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: ../../vendor/knplabs/doctrine-behaviors/config/orm-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%"
exception_controller: 'FOS\RestBundle\Controller\ExceptionController::showAction'
form:
resources:
- 'StnwDatePickerBundle:Form:fields.html.twig'
- 'XxxAppBundle:Form:fields.html.twig'
globals:
locales: "%locales%"
# 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
types:
json: Sonata\Doctrine\Types\JsonType
phone_number: Misd\PhoneNumberBundle\Doctrine\DBAL\Types\PhoneNumberType
# 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 }
sensio_framework_extra:
view:
annotations: false
fos_rest:
param_fetcher_listener: true
view:
view_response_listener: 'force'
formats:
xml: true
json: true
templating_formats:
html: true
format_listener:
rules:
- { path: ^/, priorities: [ html, json, xml ], fallback_format: ~, prefer_extension: true }
exception:
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
messages:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
allowed_methods_listener: true
access_denied_listener:
json: true
# serializer:
# serialize_null: true
body_listener: true
disable_csrf_role: ROLE_API
nelmio_api_doc:
name: Xxx REST API
sandbox:
authentication:
delivery: http
# name: apiKey
type: bearer # `basic`, `bearer` are supported
sonata_block:
default_contexts: [cms]
blocks:
# Enable the SonataAdminBundle block
sonata.admin.block.admin_list:
contexts: [admin]
sonata.admin.block.search_result:
contexts: [admin]
# Your other 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.block.service.text:
sonata.block.service.action:
sonata.block.service.rss:
sonata_admin:
title: Xxx
# title_logo: bundles/acmedemo/img/fancy_acme_logo.png
templates:
# default global templates
layout: ApplicationSonataAdminBundle::layout.html.twig
ajax: SonataAdminBundle::ajax_layout.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
search: SonataAdminBundle:Core:search.html.twig
search_result_block: SonataAdminBundle:Block:block_search_result.html.twig
dashboard:
blocks:
# display a dashboard block
- { position: left, type: sonata.admin.block.admin_list }
groups:
default:
fos_user:
label: menu.group_users
items: [sonata.user.admin.user, sonata.user.admin.group]
xxx_company:
label: menu.group_company
items: [xxx.admin.company, xxx.admin.company_category, xxx.admin.store, xxx.admin.device]
xxx_catalog:
label: menu.group_catalog
items: [xxx.admin.catalog.product, xxx.admin.catalog.product_category, xxx.admin.chip.rule]
xxx_transaction:
label: menu.group_transaction
items: [xxx.admin.transaction]
xxx_media:
label: menu.group_media
items: [sonata.media.admin.media]
xxx_news:
label: menu.group_news
items: [xxx.news.admin.news]
xxx_faq:
label: menu.group_faq
items: [xxx.faq.admin.faq]
xxx_page:
label: menu.group_page
items: [xxx_page.admin.page]
xxx_menu:
label: menu.group_menu
items: [xxx_menu.admin.menu, xxx_menu.admin.menu_type]
xxx_city:
label: menu.group_city
items: [xxx_city.admin.city]
xxx_sms_gateway:
label: menu.group_sms_gateway
items: [xxx_sms_gateway.admin.message]
security:
handler: sonata.admin.security.handler.role
# acl security information
information:
ADMIN: [MASTER]
# permissions not related to an object instance and also to be available when objects do not exist
# the DELETE admin permission means the user is allowed to batch delete objects
admin_permissions: [CREATE, LIST, DELETE, UNDELETE, EXPORT, OPERATOR, MASTER]
# permission related to the objects
object_permissions: [VIEW, EDIT, DELETE, UNDELETE, OPERATOR, MASTER, OWNER]
options:
html5_validate: true # does not use html5 validation
confirm_exit: false # disable confirmation when quitting with unsaved changes
use_select2: true # disable select2
pager_links: 5 # pager max links to display
# set to true to persist filter settings per admin module in the user's session
persist_filters: false
#read http://sonata-project.org/bundles/media/2-2/doc/reference/installation.html
sonata_media:
# 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
default_context: default
db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr
contexts:
default: # the default context is mandatory
providers:
# - sonata.media.provider.dailymotion
- sonata.media.provider.youtube
- sonata.media.provider.image
# - sonata.media.provider.file
formats: ~
small: { width: 100 , quality: 70}
big: { width: 500 , quality: 70}
cdn:
server:
path: /uploads/media # http://media.sonata-project.org/
filesystem:
local:
directory: %kernel.root_dir%/../web/uploads/media
create: false
# Notice: EntityAudit currently only works with a DBAL Connection and EntityManager named "default".
simple_things_entity_audit:
# таблицы мультиперевода автоматически НЕ цепляются, поэтому нужно указывать в ручную в этом списке
audited_entities:
- Application\Sonata\UserBundle\Entity\User
- Application\Sonata\UserBundle\Entity\Group
# If you need to exclude some entity properties from triggering a revision use:
# global_ignore_columns:
# - created_at
# - updated_at
sonata_intl:
timezone:
default: Europe/Moscow
detectors:
- sonata.intl.timezone_detector.user
- sonata.intl.timezone_detector.locale
locales:
ru: Europe/Chisinau
fos_user:
db_driver: orm # can be orm or odm
firewall_name: admin
user_class: Application\Sonata\UserBundle\Entity\User
from_email:
address: noreply#xxx.com
sender_name: Xxx Noreply
registration:
form:
type: application_sonata_user_registration
handler: fos_user.registration.form.handler.default
name: fos_user_registration_form
validation_groups: [XxxRegistration]
confirmation:
enabled: true
template: ApplicationSonataUserBundle:Registration:email.txt.twig
profile:
form:
type: application_fos_user_profile
handler: fos_user.profile.form.handler.default
name: fos_user_profile_form
validation_groups: [Authentication]
change_password:
form:
type: application_fos_user_change_password
handler: fos_user.change_password.form.handler.default
name: fos_user_change_password_form
validation_groups: [ChangePassword, Default]
group:
group_class: Application\Sonata\UserBundle\Entity\Group
group_manager: sonata.user.orm.group_manager # If you're using doctrine orm
service:
user_manager: sonata.user.orm.user_manager # If you're using doctrine orm
mailer: fos_user.mailer.twig_swift
sonata_user:
security_acl: false
class:
user: Application\Sonata\UserBundle\Entity\User
group: Application\Sonata\UserBundle\Entity\Group
profile: # Profile Form (firstname, lastname, etc ...)
form:
type: application_sonata_user_profile
handler: sonata_user.form.handler.profile
name: sonata_user_profile_form
validation_groups: [Profile]
impersonating:
route: sonata_admin_dashboard
parameters:
sonata.user.admin.user.class: Application\Sonata\UserBundle\Admin\UserAdmin
knp.doctrine_behaviors.blameable_listener.user_entity: Application\Sonata\UserBundle\Admin\UserAdmin
# sonata.user.admin.user.translation_xxxin: ApplicationUserBundle
fos_oauth_server:
db_driver: orm # Driver availables: orm, mongodb, or propel
client_class: Application\FOS\OAuthServerBundle\Entity\Client
access_token_class: Application\FOS\OAuthServerBundle\Entity\AccessToken
refresh_token_class: Application\FOS\OAuthServerBundle\Entity\RefreshToken
auth_code_class: Application\FOS\OAuthServerBundle\Entity\AuthCode
service:
user_provider: fos_user.user_manager
options:
access_token_lifetime: 3600 #seconds
token_type: Bearer
# supported_scopes: oauth_scope_scanner test1
fos_js_routing:
cache_control:
# All are optional, defaults shown
public: false # can be true (public) or false (private)
maxage: null # integer value, e.g. 300
smaxage: null # integer value, e.g. 300
expires: null # anything that can be fed to "new \DateTime($expires)", e.g. "5 minutes"
vary: [] # string or array, e.g. "Cookie" or [ Cookie, Accept ]
jms_serializer:
metadata:
auto_detection: true
directories:
SonataUserBundle:
namespace_prefix: "Sonata\\UserBundle"
path: "#ApplicationSonataUserBundle/Resources/config/serializer/SonataUserBundle"
FOSUserBundle:
namespace_prefix: "FOS\\UserBundle"
path: "#ApplicationSonataUserBundle/Resources/config/serializer/FOSUserBundle/"
white_october_pagerfanta:
exceptions_strategy:
out_of_range_page: to_http_not_found
not_valid_current_page: to_http_not_found
apy_data_grid:
limits: [20, 50, 100]
pagerfanta:
enable: true #default false
view_class: Pagerfanta\View\TwitterBootstrap3View #default Pagerfanta\View\DefaultView
options: #all options of pager fanta view constructor
prev_message : «
next_message : »
genemu_form:
date: ~
captcha: ~
# tinymce: ~
a2lix_translation_form:
locales: %locales% # [1]
required_locales: %locales% # [2]
manager_registry: doctrine # [3]
templating: "A2lixTranslationFormBundle::default.html.twig" # [4]
white_october_breadcrumbs:
viewTemplate: "XxxAppBundle:Breadcrumbs:breadcrumbs.html.twig"
separator: ""
ivory_ck_editor:
default_config: default
configs:
default:
filebrowserBrowseRoute: admin_sonata_media_media_browser
filebrowserImageBrowseRoute: admin_sonata_media_media_browser
# Display images by default when clicking the image dialog browse button
filebrowserImageBrowseRouteParameters:
provider: sonata.media.provider.image
filebrowserUploadRoute: admin_sonata_media_media_upload
filebrowserUploadRouteParameters:
provider: sonata.media.provider.file
# Upload file as image when sending a file from the image dialog
filebrowserImageUploadRoute: admin_sonata_media_media_upload
filebrowserImageUploadRouteParameters:
provider: sonata.media.provider.image
context: my-context # Optional, to upload in a custom context
xxx_transaction:
sms_confirmation: %transaction_sms_confirmation%
xxx_contact:
store_data: false
contact_class: Xxx\ContactBundle\Model\BaseContact
form:
type: application_xxx_contact
# handler: xxx_contact.form.handler.default
# name: contact_form
# validation_groups: [Default]
# subject_provider: xxx_contact.subject_provider.noop
captcha_type: genemu_captcha
#
email:
# mailer: xxx_contact.mailer.twig_swift
recipient_address: "%admin_email%" # Required
# template: XxxContactBundle:Contact:email.txt.twig
jms_i18n_routing:
default_locale: %locale%
locales: %locales%
strategy: prefix_except_default
xxx_sms_gateway:
monolog_handler: monolog.logger.sms_gateway
message:
class: Xxx\Bundle\SmsGatewayBundle\Entity\Message
manager: xxx_sms_gateway.entity.message_manager
default_gateway: bulk_sms
gateways:
bulk_sms:
sender: %sms_gateway_bulk_sms_sender%
username: %sms_gateway_bulk_sms_username%
password: %sms_gateway_bulk_sms_password%
mode:
charset: plaintext # plaintext, utf8, windows-1251
max_number_of_chars: 160 # 160 for plaintext, 70 for UTF8 and Windows 1251
# base_url: http://79.170.224.75/BulkSMSAPI/UnifunBulkSMSAPI.asmx/SendSMSNoneDigitsEncoded
base_url: http://79.170.224.75/BulkSMSAPI/UnifunBulkSMSAPI.asmx/SendSMSSimple
report:
enabled: false
mask: 31 # 1, 2, 4, 8, 16, 31
route: xxx_sms_gateway_sms_report_bulk_sms
bazinga_js_translation:
locale_fallback: %locale%
active_locales: %locales%
default_xxxin: XxxAppBundle
xxx_last_activity:
audited_entities:
# - Application\Sonata\UserBundle\Entity\User # при регистарции нет имени
- Xxx\Bundle\CompanyBundle\Entity\Company
- Xxx\Bundle\FaqBundle\Entity\Faq
- Xxx\Bundle\NewsBundle\Entity\News
Standart pagination with pagerfanta
{% if pagination.haveToPaginate %}
{{ pagerfanta(pagination, 'twitter_bootstrap3_translated') }}
{% endif %}
Standart pagination call
// return some query
$query = $this->getManager()->getQueryAllByCategory($findCompaniesByCategory);
$page = $request->query->get('page', 1);
$pagination = new Pagerfanta(new DoctrineORMAdapter($query));
$pagination
->setMaxPerPage($this->container->getParameter('items_on_page'))
->setCurrentPage($page)
;
I follow steps from my book (based on symfony 2.0.10, I'm using Symfony2.6.1 with FOSUB 2.0).
I build project with CRUD that display data from db just fine (Mountain controller inside My/BackendBundle).
Then I want display project only for logged user admin (with ROLE_SUPER_ADMIN, that exist in my for_user table inside db with CRUD data).
But when openning ../web/ its result exception Unable to find Mountain entity. from Mountain controller showAction($id)
#\src\My\BackendBundle\Controller\MountainController.php
/**
* Finds and displays a Mountain entity.
*
* #Route("/{id}", name="mountain_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('MyBackendBundle:Mountain')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Mountain entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
AppKernel.php
#\app\AppKernel.php
new FOS\UserBundle\FOSUserBundle(),
new My\UserBundle\MyUserBundle(),
new My\BackendBundle\MyBackendBundle(),
security.yml
#\app\config\security.yml
security:
providers:
fos_userbundle:
id: fos_user.user_manager
encoders:
FOS\UserBundle\Model\UserInterface: sha512
firewalls:
main:
pattern: ^/
logout: true
anonymous: true
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
login_path: /login
use_forward: false
check_path: /login_check
post_only: true
always_use_default_target_path: false
default_target_path: /
target_path_parameter: _target_path
use_referer: false
failure_path: null
failure_forward: false
username_parameter: _username
password_parameter: _password
csrf_parameter: _csrf_token
intention: authenticate
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, role: ROLE_SUPER_ADMIN }
config.yml
#\app\config\config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
framework:
#esi: ~
translator: ~
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:
# default_locale: pl
# 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%"
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 }
stof_doctrine_extensions:
default_locale: en_US
orm:
default:
tree: false
loggable: false
timestampable: false
sluggable: false
translatable: false
fos_user:
db_driver: orm
firewall_name: main
user_class: My\UserBundle\Entity\User
routing.yml
#\app\config\routing.yml
MyBackendBundle:
resource: "#MyBackendBundle/Controller/"
type: annotation
prefix: /
fos_user_security:
resource: "#FOSUserBundle/Resources/config/routing/security.xml"
parameters.yml
#\parameters.yml
parameters:
database_driver: pdo_mysql
database_host: 127.0.0.1
database_port: null
database_name: koronaziemi
database_user: root
database_password: null
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
locale: pl
secret: ThisTokenIsNotSoSecretChangeIt
Add requirements parameter to your route description and also you can skip entity fetching by leaving it for Symfony to serve you:
#\src\My\BackendBundle\Controller\MountainController.php
/**
* Finds and displays a Mountain entity.
*
* #Route("/{mountain}", name="mountain_show", requirements={"mountain": "\d+"})
* #Method("GET")
* #Template()
*/
public function showAction(Mountain $mountain)
{
$deleteForm = $this->createDeleteForm(mountain->getId());
return array(
'entity' => $mountain,
'delete_form' => $deleteForm->createView(),
);
}
Also, #Template() considered as bad practice and it is a better idea to return a Response object:
#\src\My\BackendBundle\Controller\MountainController.php
/**
* Finds and displays a Mountain entity.
*
* #Route("/{mountain}", name="mountain_show", requirements={"mountain": "\d+"})
* #Method("GET")
*/
public function showAction(Mountain $mountain)
{
$deleteForm = $this->createDeleteForm(mountain->getId());
return $this->render(
'MyBackendBundle:Mountain:show',
array(
'entity' => $mountain,
'delete_form' => $deleteForm->createView(),
)
);
}
----edit---
#Aistis with this code
/**
* #Route("/{id}", name="mountain_show", requirements={"id": "\d+"}))
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
var_dump($id);
$entity = $em->getRepository('MyBackendBundle:Mountain')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Mountain entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
it's works. But why he gets /login as a parameter?
I have a third party application (responsivefilemanager plugin for TinyMCE) that I can't re-write it using Symfony2.
I need to protect it against unauthorized users.
Is it possible to access Symfony2's session variables (user, roles , etc) from external application? How?
I tried to do session_start() and read $_SESSION variable, but it is empty!
My config.yml is:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: #ar1y4nArticleBundle/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_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
# Doctrine Configuration
doctrine:
dbal:
driver: %database_driver%
host: %database_host%
port: %database_port%
dbname: %database_name%
user: %database_user%
password: %database_password%
charset: UTF8
types: #this is about this line and line below
json: Sonata\Doctrine\Types\JsonType
# 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 }
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: ar1y4n\UserBundle\Entity\User
group:
group_class: ar1y4n\UserBundle\Entity\Group
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:
sonata.user.block.menu: # used to display the menu in profile pages
sonata.user.block.account: # used to display menu option (login option)
# Some specific block from the SonataMediaBundle
#sonata.media.block.media:
#sonata.media.block.gallery:
#sonata.media.block.feature_media:
knp_menu:
twig: # use "twig: false" to disable the Twig extension and the TwigRenderer
template: knp_menu.html.twig
templating: false # if true, enables the helper for PHP templates
default_renderer: twig # The renderer to use, list is also available by default
sonata_user:
security_acl: true
class: # Entity Classes
user: ar1y4n\UserBundle\Entity\User
group: ar1y4n\UserBundle\Entity\Group
sonata_admin:
title: My title
title_logo: bundles/ar1y4narticle/images/logo-big.png
genemu_form:
tinymce:
enabled: true
theme: modern
configs: {plugins: ["responsivefilemanager advlist autolink lists link image charmap print preview hr anchor pagebreak","searchreplace wordcount visualblocks visualchars code fullscreen","insertdatetime media nonbreaking save table contextmenu directionality", "emoticons template paste textcolor"],toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",toolbar2: "print preview media | forecolor backcolor emoticons | responsivefilemanager",image_advtab: true, external_filemanager_path:"/filemanager/",filemanager_title:"Responsive Filemanager" ,external_plugins: { "filemanager" : "/filemanager/plugin.min.js"}}
I managed to access security context by doing this:
In reponsivefilemanager/config/config.php add:
require_once '../../vendor/autoload.php';
require_once '../../app/bootstrap.php.cache';
require_once '../../app/AppKernel.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
$kernel = new AppKernel('dev', true);
//$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$kernel->boot();
$session = new \Symfony\Component\HttpFoundation\Session\Session($kernel->getContainer()->get('session.storage'));
$session->start();
$request = Request::createFromGlobals();
$request->setSession($session);
$event = new GetResponseEvent($kernel->getContainer()->get('http_kernel'),$request, HttpKernel::MASTER_REQUEST);
$firewall = $kernel->getContainer()->get('security.firewall');
$firewall->onKernelRequest($event);
if(!$kernel->getContainer()->get('security.context')->isGranted('ROLE_ADMIN')) die("Access Denied");
Of course you should change autoload.php, bootstrap.php.cache & AppKernel.php paths according to your file structure.
This has two problems:
You should use $kernel = new AppKernel('prod', false); when using prod mode (app.php) and $kernel = new AppKernel('dev', true); when using dev mode (app_dev.php)
This has a problem when a non-logged in user attempts to access filemanager and gives symfony's Access Denied error ; however, it does the job and prevents non-granted user to use the file manager
I'm working on solving the problems; and I'll post the result here.
Good luck
You can read the symfony session like this :
// start session
session_start();
// check for symfony2 attrs first
if (isset($_SESSION['_sf2_attributes'])) {
// check for security main information
if (isset($_SESSION['_sf2_attributes']['_security_main'])) {
// we are safe to go :)
// change it , to meet your path
require_once __DIR__ . '/../../../app/autoload.php';
/**
* #var Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken
*/
$security = unserialize($_SESSION['_sf2_attributes']['_security_main']);
$roles = $security->getRoles();
$user = $security->getUser();
// do your logic here
} else {
die('Access Denied');
}
} else {
die('Access Denied');
}
in config.php before session_start(); add
require_once __DIR__.'/../../../../../app/bootstrap.php.cache';
require_once __DIR__.'/../../../../../app/AppKernel.php';
use Symfony\Component\HttpFoundation\Request;
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$isSymfony2Authenticated = $kernel->getContainer()->get('security.context')->getToken() != null && ($kernel->getContainer()->get('security.context')->isGranted('ROLE_ADMIN') || $kernel->getContainer()->get('security.context')->isGranted('ROLE_SUPER_ADMIN'));
if ( ! $isSymfony2Authenticated) {
die('Access denied!');
}
This will check if user has ROLE_ADMIN or ROLE_SUPER_ADMIN
For Symfony 4.4
require dirname(__DIR__).'/../../../vendor/autoload.php';// relative path from your app
require dirname(__DIR__).'/../../../config/bootstrap.php';// relative path from your app
use App\Kernel;
use Symfony\Component\HttpFoundation\Request;
/*if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) {
Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts([$trustedHosts]);
}*/
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$kernel->handle($request);
if(!$kernel->getContainer()->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) die("Access Denied");
Symfony Session from externals:
Hello, for access from an external application to symfony session.
I hope it good, bye.
app/config/config.yml
framework:
session:
handler_id: session.handler.native_file
save_path: "%kernel.root_dir%/sessions"
PHP Class content:
/**
* #var array
*/
protected $sesion;
/**
* Obtiene los datos del usuario logeado en symfony
*
* #return string
*/
public function getSesion()
{
try
{
if (!isset($_COOKIE['PHPSESSID'])) {
throw new \Exception("No se encontro la cookie de sesion.", 1);
}
$path = '\\path\\proyect';
$archivo_sesion = $path[0].'\\app\\sessions\\sess_'.$_COOKIE['PHPSESSID'];
if (!file_exists($archivo_sesion)) {
throw new \Exception("No se encontro el archivo de sesion.", 1);
}
$sesion = file_get_contents($archivo_sesion);
$sesion = str_replace('_sf2_attributes|', '', $sesion);
$sesion = unserialize($sesion);
if (!isset($sesion['_security_default'])) {
throw new \Exception("Usuario no autorizado.", 1);
}
} catch (\Exception $e) {
header('Location: '.$sesion['_security.default.target_path'].'login');
die();
}
}