I am a student and I am very new in symfony and in stackoverflow then sorry if I do some mistakes.
Here is the error when I try to access to the page:
[Semantical Error] The annotation "#Route" in method
AppBundle\Controller\FormController::newAction() was never imported.
Did you maybe forget to add a "use" statement for this annotation? in
/home/buddy/Bachelor/RealBachelor/src/AppBundle/Controller/ (which is
being imported from
"/home/buddy/Bachelor/RealBachelor/app/config/routing.yml"). Make sure
annotations are enabled.
and here is my controller:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class SuccessController extends Controller
{
/**
* #Route("/success", name="success")
*/
public function indexAction(Request $request)
{
$id = "yeah success!!";
return $this->render('default/index.html.twig', [
'id' => $id,
]);
}
}
I don't know if is needed but here is my routing config file:
# bin/config/routing.yml
fos_user:
resource: "#FOSUserBundle/Resources/config/routing/all.xml"
app:
resource: '#AppBundle/Controller/'
type: annotation
You need to check this file:
AppBundle\Controller\FormController.php
It seems you didn't add the namespace:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
In newer Symfony versions, use
use Symfony\Component\Routing\Annotation\Route;
Please check it.
I had a problem just like yours and from a newly downloaded project with composer and symfony 3.4. It didn't start until I commented out the routing.yml file then I got the project up without problems.
I attach how it should look:
app/config/routing.yml
#app:
# resource: '#AppBundle/Controller/'
# type: annotation
You save changes then you start the server and it should work without problems!
Regards!
Your class should look like this:
/**
* #Route("/success", name="success")
*/
class SuccessController extends Controller
{
public function indexAction(Request $request)
{
$id = "yeah success!!";
return $this->render('default/index.html.twig', [
'id' => $id,
]);
}
}
Related
I'm facing a problem that I don't understand. I simply create a Controller with make:controller and everything works, but when I want to create a new method, my route annotation doesn't work (whereas the default one works normally). T
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends AbstractController
{
/**
* #Route("/default", name="default")
*/
public function index()
{
return $this->render('default/index.html.twig', [
'controller_name' => 'DefaultController',
]);
}
/**
* #Route("/", name="home")
*/
public function home() {
return $this->render('default/home.html.twig');
}
}
The / route redirects me to the default page of Symfony and any other name for the route returns the No route found error.
Also, PHPStorm tells me that Import' Symfony\Component\Routing\Annotation\Route is never used when you can see that they are there...
How to solve this ? Thanks !
Check your config/routing.yaml
I am using Symfony 3.4.0, I try to load fixtures with:
php bin/console doctrine:fixtures:load
An error occurred while creating the data, what's wrong?
This command looks for all services tagged with doctrine.fixture.orm.
There is two ways to fix this problem.
First one: any class that implements ORMFixtureInterface will automatically be registered with this tag.
<?php
namespace AppBundle\DataFixtures\ORM;
use Doctrine\Bundle\FixturesBundle\ORMFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
class LoadFixtures implements ORMFixtureInterface
{
public function load(ObjectManager $manager)
{
#your code
}
}
Second one: You need manually tag doctrine.fixture.orm to DataFixtures in sevice.yml configuration.
services:
...
# makes classes in src/AppBundle/DataFixtures available to be used as services
# and have a tag that allows actions to type-hint services
AppBundle\DataFixtures\:
resource: '../../src/AppBundle/DataFixtures'
tags: ['doctrine.fixture.orm']
I tried #Alexander's solution but it's doesn't work for me.
I had resolved the same problem by adding the tag service to the class, Symfony doc on the services.yml file bundle:
BlogBundle/Resources/config/services.yml
Services:
...
# Fixtures services
BlogBundle\DataFixtures\ORM\PostFixture:
tags: [doctrine.fixture.orm]
...
My BlogBundle/DataFixtures/ORM/PostFixture.php class :
...
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
...
class PostFixture implements FixtureInterface
{
public function load(ObjectManager $manager)
{
...
}
}
Source Inspiration : Synfony doc -> Service container -> The autoconfigure Option
Hope it'll an alternative solution
Example for reusable bundle.
src/Acme/Bundle/UserBundle/DataFixtures/ORM/DataFixtures.php
<?php
namespace Acme\Bundle\UserBundle\DataFixtures\ORM;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
class DataFixtures extends Fixture
{
/**
* Load data fixtures with the passed EntityManager
*
* #param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
#your code
}
}
in app/config/services.yml
Acme\Bundle\UserBundle\DataFixtures\:
resource: '../../src/Acme/Bundle/UserBundle/DataFixtures/'
append your fixtures data:
php bin/console doctrine:fixtures:load --append
In 4.0.1 I have to implement service configuration to show Symfony my DataFixtures folder:
in config/services.yaml
services:
...
App\DataFixtures\:
resource: '%kernel.project_dir%/src/DataFixtures'
tags: [doctrine.fixture.orm]
if my class IMPLEMENTS FixtureInterface and without this config if it is EXTENDS Fixture
~/dev/domain.lan/src/ProductBundle/DataFixtures/ORM/ProductFixture.php
<?php
namespace ProductBundle\DataFixtures\ORM;
use Doctrine\Bundle\FixturesBundle\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use ProductBundle\Entity\Product;
class ProductFixture implements FixtureInterface
{
public function load(ObjectManager $manager)
{
// create 20 products! Bam!
for ($i = 0; $i < 20; $i++) {
$product = new Product();
$product->setName('Product name' . $i);
$manager->persist($product);
}
$manager->flush();
}
}
The problem is solved it was necessary to add a service: (app/config/services.yml)
services:
# Product service
ProductBundle\:
resource: '../../src/ProductBundle/*'
exclude: '../../src/ProductBundle/{Entity,Repository,Tests}'
use Doctrine\Bundle\FixturesBundle\Fixture
class ProductFixture extends Fixture implements FixtureInterface
see documentation: http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html
After long research, found a solution.
This work with :
doctrine/doctrine-fixtures-bundle: ^3.0,
Symfony ^3.3
First
Define your Fixture.
<?php
namespace Where\MyFixtureBundle\FileFolder\IsLocated;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Nao\UserBundle\Entity\User;
class LoadData implements FixtureInterface
{
/**
* Load data fixtures with the passed EntityManager
*
* #param ObjectManager $manager
*/
public function load(ObjectManager $manager){
$object = new Entity();
$object->setFoo(bar)
...
$manager->persist($object);
$manager->flush();
}
}
Next, define a service in the bundle's service.yml file or directly in
"app/config/service.yml" (not recommanded)
# Fixtures service
your_service.name:
class: Full\Namespce\With\TheClassFixtureName
tags: [doctrine.fixture.orm] <-- important
Don't forget, just to be sure the following
composer du -o or composer dump-autoload -o
Try to execute your command now for load your data fixtures.
I also had to update the app/AppKernel.php and added the following the the bundles array:
new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle()
After read above comment, i found solution inside #GuRu answer's :
"Second one: You need manually tag doctrine.fixture.orm to DataFixtures in sevice.yml configuration".
Then implements ORMFixtureInterface in your fixtures class.
. in fact, we have to add additionnal configuration inside services.yml to solve it.
Important to know, i notice this issue in version ~3.4 of symfony.
Best regard
I'm jumping here after several years just to document for myself the mixed of solution that I found in this thread.
I experienced the same issue and find the solution by using multiple answers and I hope it will help.
This were my code:
namespace App\DataFixtures;
use App\Entity\Book;
use App\Factory\{BookFactory, UserFactory};
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
UserFactory::new()->createOne([
'email' => 'user2#user.hr',
'roles' => ['ROLE_ADMIN']
]);
UserFactory::new()->createOne([
'email' => 'user3#user.hr',
'roles' => ['ROLE_USER']
]);
BookFactory::new()->createMany(25);
$manager->flush();
}
}
so I changed replaced extends Fixture ORMFixtureInterface. So new code looks like this:
namespace App\DataFixtures;
use App\Entity\Book;
use App\Factory\{BookFactory, UserFactory};
use Doctrine\Bundle\FixturesBundle\ORMFixtureInterface;
use Doctrine\Persistence\ObjectManager;
class AppFixtures implements ORMFixtureInterface
{
public function load(ObjectManager $manager): void
{
UserFactory::new()->createOne([
'email' => 'user2#user.hr',
'roles' => ['ROLE_ADMIN']
]);
UserFactory::new()->createOne([
'email' => 'user3#user.hr',
'roles' => ['ROLE_USER']
]);
BookFactory::new()->createMany(25);
$manager->flush();
}
}
then I went to services.yml and the I inserted this:
App\DataFixtures\:
resource: '%kernel.project_dir%/src/DataFixtures'
tags: ['doctrine.fixture.orm']
so services.yml file looks like this:
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.
# 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/'
- '../src/Entity/'
- '../src/Kernel.php'
App\DataFixtures\:
resource: '%kernel.project_dir%/src/DataFixtures'
tags: ['doctrine.fixture.orm']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
and then, like #Spartacvs1 suggested, in your terminal execute this
composer dump-autoload -o
I am currently trying to override the FosUserBundle Registration Form. Indeed, after following Symfony's tutorial about it, I got this error message:
Could not load type "canapey_user_registration"
Here is my code :
namespace Canapey\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('latitude');
}
public function getParent()
{
return 'fos_user_registration';
}
public function getName()
{
return 'canapey_user_registration';
}
}
and config :
fos_user:
db_driver: orm
firewall_name: main
user_class: Canapey\UserBundle\Entity\User
registration:
form:
type: canapey_user_registration
and services :
services:
canapey_user.registration:
class: Canapey\UserBundle\Form\RegistrationType
tags:
- { name: canapey_user_registration, alias: canapey_user_registration}
After few checks, I've tried to use the service inside a controller, which worked. So it's likely that the services.yml isnt loaded while config.yml is running. And yet services.yml is imported.
So if you have any ideas?
Thank you very much!
Anyone has an idea ? Since know i have to directly write into fosuserbundle's type ....
in services.yml, change
canapey_user.registration:
with
canapey_user_registration:
I want to override some of FOSUserBundle forms ( registration form ) So I followed the documentation and I cant understand why I keep getting the same error :
Attempted to load class "RegistrationFormType" from namespace
"OC\UserBundle\Form\Type". Did you forget a "use" statement for
"FOS\UserBundle\Form\Type\RegistrationFormType"?
500 Internal Server Error - ClassNotFoundException.
These are my files:
RegistrationFormType.php:
<?php
namespace OC\UserBundle\Form\Type;
use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilder $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('telephone');
}
public function getName()
{
return 'oc_user_registration';
}
}
Service.yml of the OCUserBundle:
services:
oc_user_registration:
class: OC\UserBundle\Form\Type\RegistrationFormType
tags:
- {name: form.type, alias: oc_user_registration}
and I configured the project to use my form type when the user tries to register in the app/Ressources/config.yml:
fos_user:
db_driver: orm
firewall_name: main
user_class: OC\UserBundle\Entity\User
registration:
form:
type: oc_user_registration
Please can someone tell me what's wrong here?
Solved this. The error was that the path to the path to the FormType file wasn't the same as the namespace. Thank you anyway.
You see https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_forms.md
All is explain, I already use and is ok
add his function to your registration form type
public function getParent()
{
return 'fos_user_registration';
}
I'm starting with FOSRestBundle. I have added this routing configuration:
//Sermovi/Bundle/APIBundle/Resources/config/routing.yml
sermovi_api_homepage:
type: rest
resource: Sermovi\Bundle\APIBundle\Controller\DefaultController
//app/config/routing.yml
sermovi_api:
type: rest
prefix: /api
resource: "#SermoviAPIBundle/Resources/config/routing.yml"
And this config.yml
fos_rest:
routing_loader:
default_format: json
view:
view_response_listener: true
sensio_framework_extra:
view:
annotations: false
And this controller:
namespace Sermovi\Bundle\APIBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends FOSRestController
{
public function getArticlesAction()
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SermoviManagementBundle:Transaction')->find(776);
return array(
'entity' => $entity
);
}
}
And I'm getting this error:
[{"message":"The controller must return a response (Array(entity =>
Object(Sermovi\Bundle\ManagementBundle\Entity\Transaction))
given).","class":"LogicException","trace":[{"namespace":"","short_class":"","class":"","type":"","function":"","file":"/home/tirengarfio/workspace/sermovi/app/bootstrap.php.cache","line":2855,"args":[]},{"namespace":"Symfony\Component\HttpKernel","short_class":"HttpKernel","class":"Symfony\Component\HttpKernel\HttpKernel","type":"->","function":"handleRaw","file":"/home/tirengarfio/workspace/sermovi/app/bootstrap.php.cache","line":2817,"args":[["object","Symfony\Component\HttpFoundation\Request"],["string","1"]]},{"namespace":"Symfony\Component\HttpKernel","short_class":"HttpKernel","class":"Symfony\Component\HttpKernel\HttpKernel","type":"->","function":"handle","file":"/home/tirengarfio/workspace/sermovi/app/bootstrap.php.cache","line":2946,"args":[["object","Symfony\Component\HttpFoundation\Request"],["string","1"],["boolean",true]]},{"namespace":"Symfony\Component\HttpKernel\DependencyInjection","short_class":"ContainerAwareHttpKernel","class":"Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel","type":"->","function":"handle","file":"/home/tirengarfio/workspace/sermovi/app/bootstrap.php.cache","line":2247,"args":[["object","Symfony\Component\HttpFoundation\Request"],["string","1"],["boolean",true]]},{"namespace":"Symfony\Component\HttpKernel","short_class":"Kernel","class":"Symfony\Component\HttpKernel\Kernel","type":"->","function":"handle","file":"/home/tirengarfio/workspace/sermovi/web/app_dev.php","line":28,"args":[["object","Symfony\Component\HttpFoundation\Request"]]}]}]
EDIT:
"Could" I do something like this below? Or since FOSRestBundle is using JMSSerializerBundle I should not do it?
$serializedEntity = $this->container->get('serializer')->serialize($entity, 'json');
return new Response($serializedEntity);
There are several ways to setup your Controllers with FOSRestBundle. The way you are doing it, you must return a view. Here is a link to a rest controller on github that may help you out a bit. LiipHelloBundle has an example.
Also, I found it easiest to use the ClassResourceInterface in my controllers. This way, I return an array, and it handles all the serialization itself. It also uses your Controller name to generate the routes that are necessary, so I don't have to manually define any routes. It is my preferred way of setting up the Controller. See the doc entry here for how that works.
If you do end up using the ClassResourceInterface, be sure to include the following annotation for each action, it will make it so your returned array is serialized properly:
use FOS\RestBundle\Controller\Annotations as Rest;
//.....
/**
* #Rest\View()
*/
public function cgetAction() {}
You might even be able to do that with the way you are setting up the controller, but I haven't tried that before. Let us know if you go that way and it works.
UPDATE
For those who may be interested in using the FOSRestBundle without using the ClassResourceInterface, the problem with the controller action in the question is that it does not return a view. This should work in the action:
class DefaultController extends FOSRestController
{
public function getArticlesAction()
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SermoviManagementBundle:Transaction')->find(776);
$statusCode = 200;
$view = $this->view($entity, $statusCode);
return $this->handleView($view);
}
}