FOSUserBundle undefined method getName(); - symfony

I'm trying to install FOSUserBundle for the first time. After following the steps, I tried executing php app/console doctrine:schema:update --force. This gives me the following error. I can't understand why it's looking for getName(), it's not shown in the bundle in examples online.
PHP Fatal error: Call to undefined method music\userBundle\userBundle::getName() in /home/me/public_html/music/app/bootstrap.php.cache on line 2505
my bundle:
<?php
// src/userBundle/Entity/User.php
namespace 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;
public function __construct()
{
parent::__construct();
// your own logic
}
}

It seems the root directory of your application is interpreted as namespace.
The error output say music\userBundle::getName(), but call getName() on your entity name should be userBundle\User::getName() .
I think you have to re-build your application using the following class architecture :
YourNamespace\UserBundle
So, you entity should become
YourNamespace\UserBundle\Entity\User
and
YourNamespaceUserBundle::User
If you can, post your config.yml and security.yml files

First of all you need to make sure that you include your bundle in AppKernel.php, also should review your namespaces, during best practices your namespace should contain vendor name, bundle name, directory to class, so u should consider to set your namespace to something like this:
namespace music\userBundle\Entity;
Because for now it looks like you do something wrong:
music\userBundle\userBundle::getName()
and
namespace userBundle\Entity;
And after installing new bundles (or after any important changes) dont forget to clear you by cli command or manually. Try this, and if it doesnt helps then we will go deeper to your project structure.

Sorry seems like named the userBundle wrong, as following a video tutorial I did it manually, and forgot the extends part.
namespace music\userBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class userBundle extends Bundle
{
}

Related

"The controller must return a response" while using #Template annotation

Using Symfony Framework:
"sensio/framework-extra-bundle": "^5.1"
+
"symfony/framework-bundle": "^4.1"
with default configuration.
Receive error: The controller must return a response (Array() given).
Sample code:
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
/**
* #Route("/")
*/
class IndexController extends Controller
{
/**
* #Route("", name="index")
* #Template()
*/
public function index()
{
return [];
}
}
I tried to add:
sensio_framework_extra:
view:
annotations: true
But it doesn't work
I have same sample project with "symfony/framework-bundle": "^4.0" and it work properly.
It turns out I created a new project from scratch, but did not use the symfony/website-skeleton package that would normally install all dependencies. So it wasn't just that my #Template annotation wasn't working, it was that no templates were working because Twig wasn't installed.
I ran the command composer require twig-bundle and it solved the problem.
Take a look at the #Template annotation documentation. It states:
As of version 4.0 of the bundle, only Twig is supported by the #Template annotation (and only when not used with the Symfony Templating component -- no templating entry set in the framework configuration settings).
I imagine you are using the Symfony Templating component in which case this will not work. Or, you may also have your template file named improperly - it should be named after the controller and action name.
Better still, have a look at Symfony's Best Practices for Templates which recommends that you store templates in the templates/ directory of your root project, rather than a bundle's Resources/views/ folder. This means that you no longer reference templates like #App/Index/Index.html or use the magic #Template annotation. You would instead explicitly call your template from your controller like so:
/**
* #Route("", name="index")
*/
public function index()
{
return $this->render('index/index.html.twig');
}
Finally, and this may seem obvious, but make sure you have Twig installed in your project (composer require symfony/twig-bundle).

Use Symfony2 Validator Annotations outside of Core

How do you configure Symfony2 Validator to use annotations outside of Core?
In core you would do the following:
$container->loadFromExtension('framework', array(
'validation' => array(
'enable_annotations' => true,
),
));
Taken from: http://symfony.com/doc/2.0/book/validation.html#configuration
For now to make validation work the rules are set within the method loadValidatorMetadata(ClassMetadata $metadata), it works but I prefer annotations.
Example Entity with validation annotations and alternative php method to set validation rules:
<?php
namespace Foo\BarBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="Foo\BarBundle\Entity\Repository\FooRepository")
* #ORM\Table(name="foo")
*/
class Foo {
/**
* #ORM\Column(type="integer", name="bar")
* #Assert\Type(
* type="integer",
* message="The value {{ value }} is not a valid {{ type }}."
* )
*/
protected $bar;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('bar', new Assert\Type(array(
'type' => 'integer',
'message' => 'The value {{ value }} is not a valid {{ type }}.',
)));
}
}
Update 1
The issue now seems to be that the annotations are not being autoloaded correctly.
I load the annotations in to the namespace with:
\Doctrine\Common\Annotations\AnnotationRegistry
::registerAutoloadNamespace("Symfony\Component\Validator\Constraints\\", __DIR__.'/vendor/symfony/validator');
Then when it tries to autoload the annotations it looks for /vendor/symfony/validator/Symfony/Component/Validator/Constraints/Length.php which does not exist. The file is actually located at /vendor/symfony/validator/Constraints/Length.php
I could create a registerLoader() but would rather fix the code. When using Validator within Symfony2 Core that file location would be correct.
How do I make it autoload correctly or get composer to install Symfony2 components to the same location as core?
You need to register the Autoloader with AnnotationRegistry, so where ever you require vendor/autoload, for example bootstrap.php add the registerLoader().
//Composer libraries
$loader = require_once 'vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
Turns out the solution is quite straight forward.
The accepted answer provides a solution without giving any explaination regarding the failure.
The reason is simple. The default annotation loader which is provided by the Doctrine\Common\Annotations\AnnotationRegistry only handle PSR-0 namespaces, while the Symfony\Component\Validator\Constraints is a PSR-4 namespace. Thus, the loader fail to load the class. Registering the composer auloader with the AnnotationRegistry::registerLoader method solves the problem because that autoloader handle the PSR-4 namespaces.
You can refer to this question to get more detaits about PSR-0 and PSR-4 differences: What is the difference between PSR-0 and PSR-4?

Symfony 2.1 error: import #ORM\Table in repository

I am upgrading an application from Symfony 2.0 to Symfony 2.1, I followed this upgrade file and all works fine except that after a cache:clear I get an error when using some repositories. Here is the error:
[Semantical Error] The annotation "#ORM\Table" in class
edasiclinic\AlertesBundle\Repository\AlertesRepository was never imported. Did you maybe
forget to add a "use" statement for this annotation?
This is one example, I get this error with other repositories. I don't understand why I have to import #ORM\Table inside a repository file if I don't use annotation there.
Also if I wait for ~10 seconds and then refresh the browser, it works...
EDIT
This is the Entity:
<?php
namespace edasiclinic\DatabaseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* edasiclinic\DatabaseBundle\Entity\Alertes
*
* #ORM\Table(name="alertes")
* #ORM\Entity(repositoryClass="edasiclinic\AlertesBundle\Repository\AlertesRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Alertes
{
/**
* #var integer $id
*
* #ORM\Id
* #ORM\Column(name="idAlerta", type="integer")
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
...
}
And this the repository class:
<?php
namespace edasiclinic\AlertesBundle\Repository;
use Doctrine\ORM\EntityRepository;
use edasiclinic\DasiBundle\Funcions\AES;
class AlertesRepository extends EntityRepository
{
public function countUnread($user, $idioma, $fus)
{
// ...
}
}
Thanks
I had this very same problem today. the solution, after some googling, is apparently to include a comment block before the Repository class definition.
in your case:
/**
* AlertesRepository
*/
class AlertesRepository extends EntityRepository
{
...
}
without that comment block, you will receive the nonsensical error about "#ORM\Table". yet another Symfony/Doctrine oddity >_>
It was a PHP bug in versions prior to 5.3.8. From the symfony system requirements:
$this->addRecommendation(
version_compare($installedPhpVersion, '5.3.8', '>='),
'When using annotations you should have at least PHP 5.3.8 due to PHP bug #55156',
'Install PHP 5.3.8 or newer if your project uses annotations.'
);
See PHP bug #55156 for more details and possible workaround if you're unable to upgrade to a PHP version >= 5.3.8.
Looks like you forgot to add the use statement.
<?php
namespace Acme\MyBundle\Entity;
// Remember to include this use statement
use Doctrine\ORM\Mapping as ORM;
/**
* My Entity
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\MyBundle\Entity\MyEntityRepository")
*/
class MyEntity
{
}
For me it only hapens with certain versions of PHP and the solution was to put the Repository class in a folder above the folder of entity class

Symfony2 FOSUserBundle User entity field override

I have a problem with overriding an entity.
I need the field emailCanonical to be not be unique.
Here is what I've done:
In my UserBundle\Resources\config\doctrine\User.orm.xml I've added the following attribute-overrides configuration, according to the Doctrine2 documentation
<attribute-overrides>
<attribute-override name="emailCanonical">
<field column="email_canonical" unique="false" name="emailCanonical" />
</attribute-override>
</attribute-overrides>
Then I ran the following console commands
$ php app/console doctrine:migrations:diff
$ php app/console doctrine:migrations:migrate
Everything worked fine. emailCanonical was made non unique.
But now, when I need to generate an entity in other bundles of project, I have a strange error:
$ php app/console doctrine:generate:entities SkyModelsBundle:Category
Generating entity "Sky\Bundle\ModelsBundle\Entity\Category"
[Doctrine\ORM\Mapping\MappingException]
Invalid field override named 'emailCanonical' for class 'Sky\Bundle\UserBundle\Entity\User'.
doctrine:generate:entities [--path="..."] [--no-backup] name
However, if I remove the override settings from xml mapping, everything works fine.
You override using PHP annotations like so (This is supported starting from doctrine version 2.3 and above, please note that in the documentation it mentions that you cannot override types , however I was able to do so using the latest version of doctrine , at the time of writing it is 2.4.4):
<?php
namespace Namespace\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
/**
* User
* #ORM\Entity
* #ORM\AttributeOverrides({
* #ORM\AttributeOverride(name="id",
* column=#ORM\Column(
* name = "guest_id",
* type = "integer",
* length = 140
* )
* )
* })
*/
class myUser extends BaseUser
{
/**
* #ORM\Id()
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
}
This is specified in the documentation at: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#overrides
I believe the name attribute of the field tag is not required, since it is already specified for the attribute-override tag
Try this
<attribute-overrides>
<attribute-override name="emailCanonical">
<field column="email_canonical" unique="false" />
</attribute-override>
</attribute-overrides>
Quote from official documentation, so may be its the only way.
If you need to change the mapping (for instance to adapt the field
names to a legacy database), the only solution is to write the whole
mapping again without inheriting the mapping from the mapped
superclass.
It seems that FOSUserBundle entities aren't imported correctly into your project.
Make sure FOSUserBundle is present in "mappings" section ("doctrine" branch) of your config.yml
doctrine:
orm:
entity_managers:
default:
connection: default
mappings:
AcmeDemoBundle: ~
FOSUserBundle: ~
Got the same bug just now, and I solved it. Doctrine throws this Mappingexception in ClassMetadataInfo when it cannot find the related property (attribute or relation) in its mapping.
So, in order to override "emailCanonical" attribute, you need to use "attribute-overrides" and "attribute-override" (as you did), and redefine php class property in your entity :
<?php
...
class YourUser extends BaseUser
{
...
/**
* Email canonical
*
* #var string
*
* #ORM\Column(name="email_canonical", type="string", length=255, unique=false)
*/
protected $emailCanonical;
#EDIT : using this solution causes me another bug.
It solved the one about "Invalid field override named…", but I got another one with "Duplicate definition of column…" when trying to validate schema with php app/console doctrine:schema:validate command.
Any idea ?
Your class that extends BaseUser should be like this:
<?php
namespace Namespace\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* User
* #ORM\Entity
* #ORM\Table(name="user")
* #UniqueEntity(fields="email", message="your costum error message")
*
*/
class myUser extends BaseUser
{
/**
* #ORM\Id()
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
}
?>
I know this is an old post, but i found a solution, at least it worked for me, maybe it would be helpful for someone else.
Well, i had the same issue and i'm using a custom manager for the fos_user, in the declaration file config.yml under doctrine entity_manager custom manager i declared the mapping to FOS_userBundle, BUT what was missing is to tell FOS_user that we use a diffrent manager and that's by adding :
fos_user:
---- db_driver: orm
---- model_manager_name: MyCustom_Manager

Class ..Entity\User is not a valid entity or mapped super class

I'm getting this error when I try to clear the cache (for example):
[Doctrine\ORM\Mapping \MappingException] Class
Aib\PlatformBundle\Entity\User is not a valid entity or mapped super
class.
This is User.php:
<?php
// src/Aib/PlatformBundle/Entity/User.php
namespace Aib\PlatformBundle\Entity;
use FOS\UserBundle\Entity\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;
public function __construct()
{
parent::__construct();
// your own logic
}
}
And this is the place where User.php is stored:
javier#javier:~/programacion/aib/src/Aib/PlatformBundle/Entity$ ls
User.php UserRepository.php
This is the AppKernel.php:
public function registerBundles()
{
$bundles = array(
...
new Aib\PlatformBundle\AibPlatformBundle(),
...
);
sf 2.0.4
In my case I was missing * #ORM\Entity in my class definition.
/**
* #ORM\Entity
* #ORM\Table(name="listtype")
*/
class ListType
{
...
}
I had the exact same experience with my implementation of the FOS UserBundle and found I was able to resolve the issue by removing the MyBundle\Resources\config\doctrine folder.
I dont fully understand the cause (newbie) but think the issue is a result of having database content built in bother directions, ie from doctrine entities and by reverse engineering some tables.
I had the same problem and it turned out to be the app/config/config.yml
It needed the defintion of the default bundle as below NameBundle, then it worked fine
orm:
auto_generate_proxy_classes: %kernel.debug%
default_entity_manager: default
entity_managers:
default:
mappings:
NameBundle: ~
In my case the problem was solved by changing my servers cache from eAccelerator to APC.
Apparently eAccelerator strips all the comments from files which breaks your annotations.
I had the same error, but this was because I wasn't including the Sonata Application:
try this:
add a line to your AppKernel.php
$bundles = array(
...
new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
...
If you inherited from mapped class, you can add #ORM\SuperMappedClass in entity's annotation.
You can read most information in this article.

Resources