FOS UserBundle -> Unable to create new user - symfony

This is the very first time I use Symfony2 by myself and I think I've made a mistake when configuring the FOS User Bundle.
Looks like my User entity does not properly extend the FOS\UserBundle\Entity\User.
Here's my User class (basically the same as mentioned on the doc)
<?php
// src/Acme/UserBundle/Entity/User.php
namespace VillaPrivee\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Entity\User as BaseUser;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
}
Since I use Netbeans, I'm able to "Ctrl click" and make sure "FOS\UserBundle\Entity\User" exists.
So far, I don't see anything wrong...
But when I try to create a new user using my terminal, I get this error:
Fatal error: Call to undefined method VillaPrivee\UserBundle\Entity\User::setUsername()
in /Applications/MAMP/htdocs/VillaPrivee/vendor/friendsofsymfony/
user-bundle/FOS/UserBundle/Util/UserManipulator.php on line 50
Not sure what other details I should provide you guys with, just let me know if any other file could matter in this case.
Thanks for your help!
Edit :
<?php
namespace VillaPrivee\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class VillaPriveeUserBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
config.yml:
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: VillaPrivee\UserBundle\Entity\User

I think you extend wrong class, try with:
use FOS\UserBundle\Model\User as BaseUser;
Edit:
Yep, extending FOS\UserBundle\Entity\User is deprecated, Extend FOS\UserBundle\Model\User directly.
Documentation

Just in case someone gets the same issue as I did, i found out where the problem came from : I'm using a Mac but didn't want to get in trouble using the embedded PHP server. So I decided to use MAMP... Huge mistake!
Everything I tried using my terminal was trying to access default PHP instead of MAMP one...
Basically, I had to remove MAMP and upgrade my Mac PHP so I could use it together with Symfony.
Sorry if I'm not crystal clear, but I don't really understand it all myself...
PS: For those using MAMP, don't be as stupid as I am : your project folder is stored INSIDE your MAMP application folder. So if you trash it, you'll trash all your projects at the same time... Yep, I'm still crying about it!

I have also encountered this issue. This video really helped me.
https://knpuniversity.com/screencast/fosuserbundle-ftw
in AppKernel.php
This was my mistake:
$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 AppBundle\AppBundle(),
new FOS\UserBundle\FOSUserBundle(),
new \Acme\UserBundle\Entity\User()
);
This is the problem new \Acme\UserBundle\Entity\User()
Follow the video and you will see that you need something like this
$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 AppBundle\AppBundle(),
new FOS\UserBundle\FOSUserBundle(),
new \Acme\UserBundle\AcmeUserBundle()
);
Here is the AcmeUserBundle class:
// src/Acme/UserBundle/AcmeUserBundle.php
namespace Acme\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AcmeUserBundle extends Bundle
{
}
The UserBundle\Entity\User class is just like in the documentation
One last thing that I also saw on the view was the orm: entry in the config.yml Notice the auto_mapping: true
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
default_entity_manager: default
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
Hops this will help someone else

Related

How to use EntityManager as a service?

I use Doctrine and try to use [DependencyInjection Component][1] without Symfony (outside of a Symfony application).
I have [bootstrap.php for doctrine][2]:
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
require_once "vendor/autoload.php";
$isDevMode = false;
$paths = ["src/Project/Infrastructure/Persistence/Doctrine/Mapping/"];
$config = Setup::createXMLMetadataConfiguration($paths, $isDevMode);
$dbParams = array(
'driver' => 'pdo_mysql',
'user' => 'root',
'password' => 'root',
'dbname' => 'project',
);
$entityManager = EntityManager::create($dbParams, $config);
And I have a file to configure the container:
$containerBuilder = new ContainerBuilder();
$loader = new XmlFileLoader($containerBuilder, new FileLocator(__DIR__));
$loader->load(dirname(__DIR__) . '/config/services.xml');
And I want to get EntityManager from container such as:
$entityManager = $containerBuilder->get('doctrine.orm.entity_manager')->getManager();
But what should I do here I don't understand:
//config/services.xml
<services>
<defaults autowire="true" autoconfigure="true"/>
<service id="Doctrine\ORM\EntityManagerInterface" alias="doctrine.orm.entity_manager" public="false" />
</services>
How I can register EntityManager as a service? (I don't use Symfony just DI component)
[1]: https://symfony.com/doc/current/components/dependency_injection.html
[2]: https://www.doctrine-project.org/projects/doctrine-orm/en/2.8/reference/configuration.html#obtaining-an-entitymanager
This is basically a 'how do I use the DI component without reading the documentation' sort of question. But it is kind of interesting so here are some hints.
You need to configure a Doctrine configuration service and then inject it into the entity manager service. Both services use a static factory method so something like:
parameters:
isDevMode: true
services:
doctrine.orm.config:
public: false
class: 'Doctrine\ORM\Configuration'
factory:
- 'Doctrine\ORM\Tools\Setup'
- 'createYAMLMetadataConfiguration'
arguments:
- ['src/Entity']
- '%isDevMode%'
doctrine.orm.entity_manager:
public: true
class: 'Doctrine\ORM\EntityManager'
factory:
- 'Doctrine\ORM\EntityManager'
- 'create'
arguments:
-
driver: 'pdo_mysql'
user: db_user
password: db_password
dbname: db_name
- '#doctrine.orm.config'
I used yaml here because it's easier for me to understand. You of course can convert to xml. You never want to check in your database credentials but I'll leave that for the student to figure out. This is the sort of thing that the Doctrine bundle deals with and is why you should probably use the framework.
The test application looks like:
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
require_once 'vendor/autoload.php';
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(__DIR__));
$loader->load('config/services.yaml');
$container->compile();
$em = $container->get('doctrine.orm.entity_manager');
echo get_class($em) . "\n";
I tested it and it all works.
Enjoy.

User password not encrypted when using FOSUserBundle + EasyAdminBundle with Symfony 3.4

I use Symfony 3.4 with FOSUserBundle and EasyAdminBundle.
I've been stuck for a while on the following problem: when I create a new user via EasyAdmin, the password entered is not hashed, it remains clear in the database and in the edit form of the created user (in EasyAdmin), while there is no problem when I create a user via the form generated by FOSUserBundle (register).
My User entity :
<?php
// src/Repas/UserBundle/Entity/User.php
namespace Repas\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
}
My AdminController.php file :
<?php
namespace Repas\MenusBundle\Controller;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController as BaseAdminController;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
class AdminController extends BaseAdminController
{
public function createNewUserEntity()
{
return $this->get('fos_user.user_manager')->createUser();
}
public function persistUserEntity($user)
{
$this->get('fos_user.user_manager')->updateUser($user, false);
parent::persistEntity($user);
}
public function updateUserEntity($user)
{
$this->get('fos_user.user_manager')->updateUser($user, false);
parent::updateEntity($user);
}
}
In my config.yml file :
easy_admin:
entities:
User:
class: Repas\UserBundle\Entity\User
export_path: '%kernel.root_dir/../var/export/user'
password_encoding: { algorithm: 'bcrypt', cost: 12 }
In my security.yml file :
encoders:
Repas\UserBundle\Entity\User: bcrypt
In my routing.yml file :
fos_user:
resource: "#FOSUserBundle/Resources/config/routing/all.xml"
easy_admin_bundle:
resource: "#RepasMenusBundle/Controller/AdminController.php"
type: annotation
prefix: /admin
I've been through many forums, as well as the official docs, I think I followed everything properly but I certainly missed something.
Thank you for your help.
The EasyAdminBundle doesn't define an option to encrypt the password, it only provides options to save the entities (a crud) which you can extend by defining custom actions based on routes or actions inside an overrided AdminController in order to integrate with FOSUserBundle.
Example
easy_admin:
entities:
User:
list:
actions:
- { name: 'create_user', type: 'route' } //or nothing on type to use the action option
At this point you already have either a defined controller accessible by route or an overriden controller which handles the specified User actions. You only need to use the FOSUser methods to encrypt the password properly, as read in this doc.
Hope it helps!
Ok, I guess my mistake is that in the form generated by Easyadmin to create a new user, Easyadmin generates a field named "password" instead of "plainPassword" which is the one FOSUser uses to encrypt the entered password. So I think I just have to create a new "plainPassword" field in my "Easyadmin new user" form and enter the user password in that field to encrypt it. Then the encrypted password will be stored in "password" field of the database.
I will tell you if that is the solution.

How to get autocompletion for container using phpstorm and symfony2 plugin?

I use phpstorm. When developing a symfony2 application I am used to the symfony2 plugin providing an autocompletion for container services:
[
This offers completion on the returned objects as well.
Is there a way to get the service completion to work when using the container component in a non-symfony PHP project that uses only parts of the symfony2 components, i.e. the container component?
I know that in phpstorm's settings:
Other Settings > Symfony2 Plugins > Container
I could add additonal xml container files, yet I have no clue what it should look like.
How would I create such a file?
For instance, I create a container by:
/**
* #return ContainerBuilder
* #todo Initialize the container on a more reasonable place
*/
private function createServiceContainer()
{
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(ROOT_PATH . '/config'));
$loader->load('services.yml');
return $container;
}
And my services.yml looks like this:
services:
redis:
class: App\Framework\RedisService
doctrine:
class: DoctrineService
factory: [\App\Database\DoctrineService, getDoctrine]
How could I create a container.xml that would be understood by the symfony2 plugin and offer me the two services redis and doctrine in the container?
That XML file is created by the ContainerBuilderDebugDumpPass compiler pass in the Symfony2 Standard Edition, and you can see that it use the XmlDumper to create the file.
I have created an command:
<?php
namespace App\Command;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ContainerBuilderDebugDumpPass;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
/**
* ContainerRefreshCommand
**/
class ContainerRefreshCommand extends Command
{
/**
* Configures the current command.
*/
protected function configure()
{
$this
->setName('container:refresh')
->setDescription('refreshes the container file for usage with phpstorm');
}
/**
* #param InputInterface $input
* #param OutputInterface $output
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(ROOT_PATH . '/config'));
$loader->load('services.yml');
$container->setParameter('debug.container.dump', ROOT_PATH . '/dev/appDevDebugProjectContainer.xml');
$containerFile = new ContainerBuilderDebugDumpPass();
$containerFile->process($container);
}
}
I have then added the file from my project root:
./dev/appDevDebugProjectContainer.xml
in the container definition.
I then had to change the class name of the doctrine service. It appears to be anything goes there, yet this string is what the symfony2 plugins uses to detect the service.
I then got auto-completion for container services.
One has to note that the class property in services.yml is important as well. Since the object I actually get by container->get('doctrine'), is an instance of an EntityManager I have to define this way to get autocompletion:
doctrine:
class: Doctrine\ORM\EntityManager
factory: [\App\Database\DoctrineService, getDoctrine]

creating custom repository fos elastic search

im trying to make a simple custom repository in order to understand how elastic search repository works. the documentation is pretty straight forward but i still dont understand how it works, im getting this error ´The service definition "fos_elastica.manager" does not exist.´. so far i think my problem is in the controller since i dont understand how to intialize them, also i would like to know if im in the right way in my configuration of the custom repository and the simple query i made.
im getting this error with this configuration whenever i try to make a search,
The service definition "fos_elastica.manager" does not exist.
this is my configuration so far:
//app/config.yml
fos_elastica:
clients:
default: { host: localhost, port: 9200 }
indexes:
sava:
client: default
types:
blog:
mappings:
id:
type: integer
body : ~
title : ~
tags: ~
persistence:
identifier: id
driver: orm
model: sava\BlogBundle\Entity\TblPost
finder: ~
provider: ~
listener: ~
repository: sava\BlogBundle\SearchRepository\TblPostRepository
this is my controller action:
namespace sava\BlogBundle\Controller;
//custom querys
use FOS\ElasticaBundle\Manager\RepositoryManager;
use FOS\ElasticaBundle\Repository;
//
use Symfony\Component\DependencyInjection\ContainerBuilder;
class TblPostController extends Controller
{
public function getPostAction(Request $request)
{
$container = new ContainerBuilder();
$repositoryManager = $container->get('fos_elastica.manager');
$repository = $repositoryManager->getRepository('BlogBundle:TblPost');
$items2 = $repository->matchExact($categoria,$searchQuery );
return $this->render('savaBlogBundle:TblPost:index.html.twig', array(
'results' => $items2, 'entities' => $items2
));
}
this is my post repository:
<?php
namespace sava\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\ElasticaBundle\Repository;
class TblPostRepository extends FOS\ElasticaBundle\Repository
{
public function matchExact($campo, $searchQuery) {
//$finder = $this->get('fos_elastica.finder.sava.blog');
$query = new Query();
if($searchQuery=='')
{
$innerQuery = new Query\MatchAll();
}
else{
$innerQuery = new Query\Match();
$innerQuery->setField( $campo , array('query' => $searchQuery));
}
$query->setQuery($innerQuery);
$query->setSize(1000000);
$query->setExplain(true);
return $this->find($query);
}
}
and since im using yml this is my tblpost.orm, i did generate my entities.
whenever i do the get postaction it throws me that it cant find the container, and i dont see an example in how to properly intiaze it, also is this is how you make a custom query?
EDIT 1:
so i changed this:
$container = new ContainerBuilder();
$repositoryManager = $container->get('fos_elastica.manager');
to this:
$elastica = $this->container->get('fos_elastica.manager');// single entry point, no fancy services
$SearchRepository = $elastica->getRepository('savaBlogBundle:TblPostRepository');// single type
and im getting this error:
No search finder configured for sava\BlogBundle\Entity\TblPostRepository
I've just had the same issue, the soultion is that instead of savaBlogBundle:TblPostRepository you should use your entity, for example:
$SearchRepository = $elastica->getRepository('savaBlogBundle:TblPost`)
According your fatal error in title of the issue enter link description here
The main problem why did you get that mistake is that, you assigned the same TblPostRepository in (doctrine config for entity) and in fos_elastica.

Mapping Exception : Class does not exist Symfony2 Deployment

I have a working Project on localhost but when I deployed the project I received this error and I have no idea what's causing this to happen.
MappingException: Class 'PremiumPharma\SystemBundle\Entity\User' does not exist
this is the stacktrace
in /home/sy2/public_html/temp/symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php line 96
at MappingException::nonExistingClass('PremiumPharma\SystemBundle\Entity\User') in /home/sy2/public_html/temp/symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php line 43
at RuntimeReflectionService->getParentClasses('PremiumPharma\SystemBundle\Entity\User') in /home/sy2/public_html/temp/symfony/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php line 267
Edit 1
I did notice some errors in the profiler as it said 5 invalid entities and there were some mapping errors and I got them fixed. After re-uploading I still have the same issue. I also tried to empty the cache but I still receive the same error.
Edit 2
here is my appKernal
<?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 PremiumPharma\SystemBundle\PremiumPharmaSystemBundle(),
new FOS\UserBundle\FOSUserBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
$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');
}
}
Edit 3
As per J.Mose last comment it was a unix/windows conflict as my local machine was windows and the server was Unix. I had to rename all files to match exactly the classname.
Did you deploy an older version on this environment ?
If yes, did you delete all application's files before deploying ? If an older version of an entity doesn't exist in your project anymore (or renamed), it can provoke that kind of mapping error.
Alternatively, check in your AppKernel.php if the bundle with the entity is enabled on all environnment.
Further, if application is deployed on a Unix environnement (against a local Windows), check if your entity's name is exactly the same as the php file (cause Windows is case insensitive)
this problem has just happened to me and i have fixed it by adding the vendor name to the directory path in the config.yml file.
Step 5: Configure the FOSUserBundle
app/config/config.yml
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: AppBundle\Entity\User
change the appBundle to Vendor\NameofYourBundle\Entity\User
This error was show me when I used EasyAdminBundle and FOSUserBundle with Symfony 3.3.x .
The solution is simple:
First is necessary verification app/config/config.yml in my case the error was the name of the Bundle:
fos_user:
db_driver: orm # other valid values are 'mongodb' and 'couchdb'
firewall_name: main
user_class: BackendBundle\Entity\User
And after clean of cache:
php bin/console cache:warmup
This was my solution

Resources