I have a Symfony web application written in Symfony 2.8.
All translations work correctly in dev mode ,But the translations of second language not loading in production mode.
If I enable debug in app.php , translations will load completely.
$kernel = new AppKernel('prod', false);
TO
$kernel = new AppKernel('prod', true);
But it is not a good choice.
My config.yml is:
parameters:
locale: fa
framework:
#esi: ~
translator: { fallbacks: ["%locale%" , en] }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
I put the messages.fa.yml and messages.en.yml files in app directory.
Try follow my instructions:
1) Move your trans.yml files into src->nameBundle->Resources->translations
2) In src->nameBunndle create or update DependencyInjection folder
3) In DependencyInjection folder create Configuration.php and NameExtension.php where name is your name of bundle.
4) Code Configuration.php :
<?php
namespace NameBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {#link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {#inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('name'); // name you bundle
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
5) Code NameExtension.php :
<?php
namespace NameBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {#link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class NameExtension extends Extension
{
/**
* {#inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
Related
I have a problem with my application after I moved it to docker container. I newbie with Symfony and I cannot understand where the problem is.
After I want to call my UserController index action my browser throws an error:
Controller "App\Controller\UserController" has required constructor arguments and does not exist in the container. Did you forget to define such a service?
Too few arguments to function App\Controller\UserController::__construct(), 0 passed in /projekty/taskit/vendor/symfony/http-kernel/Controller/ControllerResolver.php on line 133 and exactly 1 expected
My services.yaml file:
parameters:
locale: 'en'
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
App\Entity\UserRepositoryInterface: '#App\DTO\UserAssembler'
UserController.php file
<?php
namespace App\Controller;
use App\Service\UserService;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class UserController
* #package App\Controller
*/
class UserController extends AbstractController
{
/**
* #var UserService
*/
private $userService;
/**
* #param UserService $userService
*/
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
/**
* #Route("/users/", name="users_index")
*/
public function index()
{
$users = $this->userService->findAll();
return $this->render('user/index.html.twig', array('users' => $users));
}
}
And my UserService.php file code
<?php
namespace App\Service;
use App\Entity\UserRepositoryInterface;
use Doctrine\ORM\EntityNotFoundException;
/**
* Class UserService
* #package App\Service
*/
class UserService
{
/**
* #var UserRepositoryInterface
*/
private $userRepository;
/**
* #param UserRepositoryInterface $userRepository
*/
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* #return array
* #throws EntityNotFoundException
*/
public function findAll() : array
{
$users = $this->userRepository->findAll();
if (is_null($users)) {
throw new EntityNotFoundException('Table users is empty');
}
return $users;
}
}
It seems to me you are doing a lot of unnecessary things, which are already part of the framework. Like your service, what does it do? You can call your repositories directly from your controller. And in your controller, you are declaring variables and constructing which is also unnecessary. Just use dependency injection in your function in the controller. This little bit of code should work and replace both your controller and your service (which again, you can get rid of).
<?php
namespace App\Controller;
use App\Repository\UserRepository;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class UserController
* #package App\Controller
*/
class UserController extends AbstractController
{
/**
* #Route("/users/", name="users_index")
*/
public function index(UserRepository $userRepository)
{
$users = $this->userRepository->findAll();
return $this->render('user/index.html.twig', array('users' => $users));
}
}
I'm trying to configure Sonata admin bundle, but I'm having this error:
Attempted to load class "ProductAdmin" from namespace
"Admin\AdminBundle\Admin". Did you forget a "use" statement for
another namespace?
protected function getSonata_Admin_ProductService() {
$instance = new \Admin\AdminBundle\Admin\ProductAdmin('sonata.admin.product', 'Admin\AdminBundle\Entity\Product', 'SonataAdminBundle:CRUD');
$instance->setTranslationDomain('AdminAdminBundle');
$instance->setFormTheme(array(0 => 'SonataDoctrineORMAdminBundle:Form:form_admin_fields.html.twig'));
}
Someone have an idea how to sloved this error ?
Thank you
Config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: #AdminAdminBundle/Resources/config/admin.yml }
# app/config/config.yml
sonata_block:
default_contexts: [cms]
blocks:
# Enable the SonataAdminBundle block
sonata.admin.block.admin_list:
contexts: [admin]
# Your other blocks
Admin.yml
services:
sonata.admin.Product:
class: Admin\AdminBundle\Admin\ProductAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: "Content", label: "Product" }
arguments:
- ~
- Admin\AdminBundle\Entity\Product
- ~
calls:
- [ setTranslationDomain, [AdminAdminBundle]]
ProductAdmin.php
<?php
// src/Acme/DemoBundle/Admin/PostAdmin.php
namespace Admin\AdminBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class ProductAdmin extends Admin
{
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title', 'text', array('label' => 'Post Title'))
->add('author', 'entity', array('class' => 'Admin\AdminBundle\Entity\Product'))
->add('body') //if no type is specified, SonataAdminBundle tries to guess it
;
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('title')
->add('author')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('title')
->add('slug')
->add('author')
;
}
}
AdminAdminExtension.php
<?php
namespace Admin\AdminBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {#link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class AdminAdminExtension extends Extension
{
/**
* {#inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
$loader->load('admin.yml');
}
}
autoload.php
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;
/**
* #var ClassLoader $loader
*/
$loader = require __DIR__.'/../vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
The error indicates that your class file could not be autoloaded properly. Check if the namespace matches your path, and when in doubt, add a file to the root of your project loading the class to check whether the autoload config works:
<?php
require_once 'vendor/autoload.php';
var_dump(class_exists('a\b\c'));
The fact that your source file states another path than your namespace structure indicates that your class is in the wrong place.
i have an error starting with Symfony2.
InvalidArgumentException in YamlFileLoader.php line 356:
There is no extension able to load the configuration for "services" (in /Users/jm/Documents/Websites/www.brsymfony.dev/src/CalcBundle/DependencyInjection/../Resources/config/services.yml). Looked for namespace "services", found none
My services.yml look like and it has whitespaces correctly:
services:
Calculator:
class: CalcBundle\Services\Calculator
arguments:
- #doctrine.orm.default_entity_manager
ListOperations:
class: CalcBundle\Services\ListOperations
arguments:
- #doctrine.orm.default_entity_manager
Can anyone help me?
--
Yes, i have this code on CalcExtension.php inside DependencyInjection folder:
<?php
namespace CalcBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Class AppExtension
*/
class CalcExtension extends Extension
{
/**
* Loads a specific configuration.
*
* #param array $config An array of configuration values
* #param ContainerBuilder $container A ContainerBuilder instance
*
* #throws \InvalidArgumentException When provided tag is not defined in this extension
*
* #api
*/
public function load(array $config, ContainerBuilder $container)
{
$loader = new YamlFileLoader(
$container,
new FileLocator(__DIR__ . '/../Resources/config')
);
$loader->load('services.yml');
}
}
Thanks in advance :)
Have you created the extension on the DependencyInjection folder? Should be CalcBundle/DependencyInjection/CalcExtension.php
You have the documentation with examples here
http://symfony.com/doc/current/cookbook/bundles/extension.html
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
The services.yml should be located on CalcBundle/Resources/config/services.yml
Be careful because examples are creating parameters and services together into config.yml, you have to adapt it to your case (services.yml and parameters.yml separated, I would recommend your way)
You have the documentation with examples here
https://symfony.com/doc/current/book/service_container.html
I obtained this error when I want to create a config paramter to a bundle.
Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
There is no extension able to load the configuration for
"mrc_morales_tyre"
This is the code:
app/config/config.yml
mrc_morales_tyre:
db_driver: orm
Configuration.php
namespace MrcMorales\TyreBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {#link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {#inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('mrc_morales_tyre');
$supportedDrivers = array('orm');
$rootNode
->children()
->scalarNode('db_driver')
->validate()
->ifNotInArray($supportedDrivers)
->thenInvalid('The driver %s is not supported. Please choose one of '.json_encode($supportedDrivers))
->end()
->end()
->end();
return $treeBuilder;
}
}
TyreExtension.php
namespace MrcMorales\TyreBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\Config\Definition\Processor;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {#link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class TyreExtension extends Extension
{
/**
* {#inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
}
}
TyreBundle.php
namespace MrcMorales\TyreBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use MrcMorales\TyreBundle\DependencyInjection\Compiler\ValidationPass;
class TyreBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ValidationPass());
}
}
ValidationPass is to load validation.yml in not usual folder and it works.
Thanks
Resolved:
Symfony by default expects than config var name is the name of extension, in this case tyre.
Then I need to change the Extension name to MrcMoralesTyreExtension but then we need override the method getContainerExtension() in:
TyreBundle.php
public function getContainerExtension()
{
return new MrcMoralesTyreExtension();
}
I am new with Symfony2 and FOSUserBundle. I am using Symfony2 version 2.4.1. I would like to extend FOSUserBundle in a few ways. I want to add fields to the registration form, some fields i would like to add to the user table which contains username and password but i would like to add fields that get added to a different table. (I think i have to rewrite the registerController??)
Currently i have inherited FOSUserBundle into my own UserBundle. I have tried to simply add fields to the current registration form by following the documentation but i keep returning this error.
Could not load type "acme_user_registration"
// src/Fixie/UserBundle/Entity/User.php
<?php
namespace Fixie\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your name.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max="255",
* minMessage="The name is too short.",
* maxMessage="The name is too long.",
* groups={"Registration", "Profile"}
* )
*/
protected $name;
public function __construct()
{
parent::__construct();
// your own logic
}
}
I then add the name field to the form builder
// src/Fixie/UserBundle/Form/Type/RegistrationFormType.php
<?php
namespace Fixie\UserBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
// add your custom field
$builder->add('name');
}
public function getName()
{
return 'acme_user_registration';
}
}
I then go on to declare the custom form type:
// src/Fixie/UserBundle/Resources/config/services.yml
services:
acme_user.registration.form.type:
class: Fixie\UserBundle\Form\Type\RegistrationFormType
arguments: [%fos_user.model.user.class%]
tags:
- { name: form.type, alias: acme_user_registration }
Then updated config:
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: Fixie\UserBundle\Entity\User
registration:
form:
type: acme_user_registration
//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 Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Fixie\WelcomeBundle\WelcomeBundle(),
new Fixie\UserBundle\UserBundle(),
new FOS\UserBundle\FOSUserBundle(),
);
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;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
// Fixie/UserBundle/UserBundle.php
<?php
namespace Fixie\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class UserBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
My main questions are:
Can anyone see an error with my current code?
In relation to extending the form to have multiple fields being stored in multiple tables. What are the step i have to take? Do i rewrite the logic of the controller and the form???
Any help would be very much appreciated.
Ok.
In appKerenl.php you have
new Fixie\UserBundle\UserBundle(),
But in service.yml
class: Acme\UserBundle\Form\Type\RegistrationFormType
Maybe it should be:
class: Fixie\UserBundle\Form\Type\RegistrationFormType
If in result of command app/console container:debug you can't see acme_user.registration.form.type it means that your service don't register and fos_user can't see you service, and can't find your form type.
My UserBundle store in Webmil/Joint/UserBundle. In UserBundle folder I have file WebmilJointUserBundle.php
My file:
<?php
namespace Webmil\Joint\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class WebmilJointUserBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
So I think that your problem in this file. Can you compare file and your file, and maybe you will find error.
With me it was that i had already a services.yml in app/config, so the one in my bundle was ignored. In the end I added the registry to this file
# app/config/services.yml
services:
# [other already existing services]
acme_user.registration.form.type:
class: Acme\UserBundle\Form\Type\RegistrationFormType
tags:
- { name: form.type, alias: acme_user_registration }